Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using named parameters in node.js

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
{
like image 296
guagay_wk Avatar asked Feb 28 '16 08:02

guagay_wk


2 Answers

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.

like image 67
6502 Avatar answered Oct 04 '22 05:10

6502


It is easier with ES6. nodejs > 6.5 supports these features.

You should check out this link:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

The exact usage you want to use is implemented. However I would not recommend it.

The code below (taken from the link above) is a better practice because you don't have to remember in which order you should write the parameters.

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
 // do some chart drawing
}

you can use this function by doing:

const cords = { x: 5, y: 30 }
drawES6Chart({ size: 'small', cords: cords })

This way functions get more understandable and it gets even better if you have variables named size, cords and radius. Then you can do this using object shorthand.

// define vars here
drawES6Chart({ cords, size, radius })

order does not matter.

like image 17
Utku Turunç Avatar answered Oct 03 '22 05:10

Utku Turunç