Node.js Named Parameters

Named parameters are a handy feature that have existed in other loosely typed languages such as Python for some time. With the feature called destructuring assignment available in newer versions of Node.js, we gain the ability to do things like this:

const { a } = { a: "b" };
console.log(a); // prints 'b'

This is useful but we can also use this in function definitions:

function func1({ a, b = 3 }) {
  console.log(a, b);
}

function func2({ b }) {
  console.log(b);
}

func1({ b: 2, a: 1 }); // prints '1 2'
func1({ a: 1 }); // prints '1 3'
func2({ b: 2, a: 1 }); // prints '2'

We can rearrange or omit parameters as needed. One feature Node.js still does not have is runtime parameter validation. If all parameters are omitted, the interpreter will not complain.

An equivalent function definition in Python would look like this:

def func(a, b):
    print('{} {}'.format(a, b))

func(b=2, a=1) # prints '1 2'

The difference between the Node.js and Python examples is that if either parameter is omitted here, an error will be raised.

If anyone has an idiomatic and DRY approach for parameter validation in Node.js, I would love to hear it.

Comments