DEV Community

Andrew Usher
Andrew Usher

Posted on

How To Use Default Function Parameter Values In JS

Function parameters are undefined by default in JavaScript. Sometimes, you want to define a default parameter in this case. Before ES6 (also known as ES2015), creating default paramaters was a little tedious:

function createName(firstName, lastName) {
  firstName = typeof firstName === 'undefined' ? 'Jane' : firstName;
  secondName = typeof secondName === 'undefined' ? 'Doe' : secondName;

  return firstName + ' ' + secondName;
}

console.log(createName()); // Jane Doe
Enter fullscreen mode Exit fullscreen mode

With the introduction of default parameter values in ES6, the above could be simplified to:

function createName(firstName = 'Jane', lastName = 'Doe') {  
  return firstName + ' ' + secondName;
}

console.log(createName()); // Jane Doe
Enter fullscreen mode Exit fullscreen mode

Top comments (0)