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
{
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With