How To Use Default Function Parameter Values In JS

andrewusher

Andrew Usher

Posted on May 8, 2022

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
💖 đŸ’Ē 🙅 🚩
andrewusher
Andrew Usher

Posted on May 8, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related