Default Parameters

Image taken from Unsplash

Default Parameters


In ES6, we can give default value to function's parameters.

With the old syntax, this is how we create default value to a parameter.

// traditional
var sayGoodbye = function (name) {
  name = name !== undefined ? name : ‘Lorem Ipsum’;
  return `Bye bye ${name}`
}

Now, let's refactor using ES6 default parameter!

// es6
const sayGoodbye = (name = ‘Lorem Ipsum’ ) => `Bye bye ${name}`
console.log(sayGoodbye()); // Bye bye Lorem Ipsum
console.log(sayGoodbye(‘Bambang’)); // Bye bye Bambang

It's so simple and easy to understand. This also helps you to handle error in advance when you forget to assign the parameter.