Default Parameters In JavaScript

JavaScript has always allowed you to define default values for function parameters, but you had to jump through some hoops. You had to check whether an argument was provided. If it wasn’t provided, the parameter would be undefined. So you’d check whether the parameter was undefined, and if so, you’d set it to the default value you wanted.

Like so:

function addEndPunctuation(sentence, endPunctuation) {
  if (typeof endPunctuation === 'undefined') {
    endPunctuation = '.';
  }

  return sentence + endPunctuation;
}

ECMAScript 2015 introduces some nice new syntax for accomplishing the same result:

function addEndPunctuation(sentence, endPunctuation = '.') {
  return sentence + endPunctuation;
}

Much cleaner.

Fun bonus: The new default parameter syntax allows you to use previous parameters as defaults!

Dig it:

function funkyFunc(foo = 'foo', bar = foo) {
  console.log('foo: ' + foo);
  console.log('bar: ' + bar);
}

funkyFunc(); // prints "foo: foo" and "bar: foo"
funkyFunc('bar'); // prints "foo: bar" and "bar: bar"

Neat.