How to Use Named Parameters in JavaScript
Apr 16, 2021
JavaScript, by default, does not support named parameters.
However, you can do something similar using object literals and destructuring.
You can avoid errors when calling the function without any arguments by
assigning the object to the empty object, {}
, even if you have default
values set up.
function example({ arg1 = 1, arg2 = 2, arg3 = 3 } = {}) {
return { arg1, arg2, arg3 };
}
function problem({failure = true}) {
return failure;
}
problem(); //TypeError: Cannot read property 'failure' of undefined
example({ arg2: 4, arg1: 2 }); // { arg1: 2, arg2: 4, arg3: 3 }
example(); // { arg1: 1, arg2: 2, arg3: 3 }
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard