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
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
If you liked this article and think others should read it, please share it on Twitter!