O'Reilly logo

Hands-On Microservices with Node.js by Diogo Resende

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Default function parameters

There's no longer the need to use logical operators or check argument types to define default argument values. They can be defined directly in the prototype:

function pad(text, len, char = " ") {    return text.substr(0, len) +           (text.length < len ? char.repeat(text.length - len) : "");}pad("John", 10, "=");

If you've developed in languages like Python before, remember default arguments in JavaScript are evaluated at call time, not when defining the function. This means a new object is created every time:

function add(value, list = []) {    list.push(value);    return list;}add(1); // [ 1 ]add(2); // [ 2 ] , not [ 1, 2 ]

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required