JavaScript doesn’t have named parameters concept. But you can do something similar using object literals and restructuring.
fun({...})
In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:
JavaScript named parameters
Simple example 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.
<!DOCTYPE html>
<html>
<body>
<script>
function example({ arg1 = 1, arg2 = 2, arg3 = 3 } = {}) {
return { arg1, arg2, arg3 };
}
function problem({failure = true}) {
return failure;
}
console.log(example({ arg2: 4, arg1: 2 }));
console.log(example());
problem(); //TypeError: Cannot read property 'failure' of undefined
</script>
</body>
</html>
Output:

Do comment if you have any doubts or suggestions on this JS parameters topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version