How To Use Default Function Parameter Values In JS
Andrew Usher
Posted on May 8, 2022
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
đ đĒ đ
đŠ
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
javascript Can Node.js Really Handle Millions of Users? The Ultimate Guide to Massive Scale Applications
November 28, 2024
javascript Alternative to AbortController for Handling Async Timeouts in JavaScript
November 27, 2024