I always wished for default value support in JavaScript function parameters. Every time I came across a default value requirement, the OR operator did its role.
1
2
3
4
5
6
|
function show (message) { message = message || "I am not assigned" ; console.log(message); } show(); // "I am not assigned" show( 'Boom' ); // "Boom" |
We do not have to default assign in this way from ES6. Here is the updated code as per ES6.
1
2
3
4
5
|
function show (message = "I am not assigned" ) { console.log(message); } show(); // "I am not assigned" show( 'Boom' ); // "Boom" |
But there is a difference in working of 2 code segments. In the traditional method(first method), "I am not assigned"
will be printed in following cases.
- No argument is passed
- Any falsy value is passed like empty string,
undefined
, 0,false
,null
In the new technique, "I am not assigned"
will be printed only when we are not passing any values or explicitly passing undefined
.
Summary: This new default argument assignment helps to deliver more readable code.
Recent Comments