ES6 provides a new syntax to assign default values to function parameters. You might be familiar with this concept from languages like Ruby, PHP or C++ and it’s about time that this was baked into the language.

One of the ways of checking for default values in ES5 code was to check if the parameter was undefined. Here is a contrived example:

function makeRice( type ) {
  var type = type === undefined ? 'white' : type;
  console.log( 'making ' + type + ' rice' );
}

makeRice(); // making white rice

Let’s look at the same example using default function parameters and some ES6 template strings sugar.

function makeRice( type = 'white' ) {
  console.log( `making ${type} rice` );
}

makeRice(); // making white rice

makeRice( 'brown' ); // making brown rice

Default value expressions

Default values can be valid expressions and even functions. The contrived code samples below demonstrates this.

function calculate( x = 3, y = 2, z = x * y ) {
  console.log( z );  
}

calculate(); // 6
function makeRice( type = defaultRiceType() ) {
  console.log( `making ${type} rice` );
}

function defaultRiceType() {
  return 'white';
}

makeRice(); // making white rice