Using named parameters in node.js

user781486 picture user781486 · Feb 28, 2016 · Viewed 12.9k times · Source

I am using node.js v4.3.1

I would like to use named parameters in calling functions as they are more readable.

In python, I can call a function in this manner;

info(spacing=15, width=46)

How do I do the same in node.js?

My javascript function looks something like this;

function info(spacing, width)
{
   //implementation
{

Answer

6502 picture 6502 · Feb 28, 2016

The standard Javascript way is to pass an "options" object like

info({spacing:15, width:46});

used in the code with

function info(options) {
    var spacing = options.spacing || 0;
    var width = options.width || "50%";
    ...
}

as missing keys in objects return undefined that is "falsy".

Note that passing values that are "falsy" can be problematic with this kind of code... so if this is needed you have to write more sophisticated code like

var width = options.hasOwnProperty("width") ? options.width : "50%";

or

var width = "width" in options ? options.width : "50%";

depending on if you want to support inherited options or not.

Pay also attention that every "standard" object in Javascript inherits a constructor property, so don't name an option that way.