How to use keyword arguments in JavaScript

Passing an Object named options to a function instead of separate arguments is one of the oldest tricks in the book, by also assigning an empty object by default you also reduce the amount of if statements needed in the top of the function. But a year ago I learned how combining this with object deconstruction made it so much more elegant.

Languages like Python and OpenSCAD have built in support for keyword arguments, JavaScript does not have that, but we can almost get there with the help of destructuring assignments.

The only thing needed is:

function parseMarkdown({markdown, lists = true, tables = true, dropHeading = true, onlyHeading = true, codeBlocks = true} = {}) {
  // Do things with your destructured local variables

Note that since we are destructuring we need to use = to assign the default values over the : that is used when we create an object, in the beginning it might be easy to mix them up.

Now this function can be called with an object with any number of arguments and in any chosen order.

const markdown = `
# The first heading

The first paragraph.

* First item
* Second item

const everything = parseMarkdown({markdown});
const heading = parseMarkdown({markdown, onlyHeading: true});
const body = parseMarkdown({markdown, dropHeading: true});

Have a good one!