Default parameter values for functions

With ES2015, it is also possible to define default parameter values for functions. The following is an example:

function sum(x = 1, y = 2, z = 3) { 
  return x + y + z; 
} 
console.log(sum(4, 2)); // outputs 9 

As we are not passing z as a parameter, it will have a value of 3 by default. So, 4 + 2 + 3 == 9.

Before ES2015, we would have to write the preceding function as in the following code:

function sum(x, y, z) { 
  if (x === undefined) x = 1; 
  if (y === undefined) y = 2; 
  if (z === undefined) z = 3; 
  return x + y + z; 
} 

Or, we could also write the code as follows:

function sum() { var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var y = arguments.length > 1 && arguments[1] !== ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.