3 ms·
That's because default params in JS are essentially syntactic sugar ex - function example(a = 1) { ... } behaves the same as function example(a) {
by horsawlarway 6y ago
That's because default params in JS are essentially syntactic sugar ex -
function example(a = 1) {
...
}
behaves the same as
function example(a) {
a = (typeof a !== 'undefined') ? a : 1
...
}
- sorahn 6y agoWhich also means the suggestion to use ?? has a different result then using a default param. ?? will catch both null and undefined, where as a default parameter will only trigger on undefined.
- horsawlarway 6y agoYup, you're absolutely correct. Null is considered a valid value for a default param. function test(a = 1) { console.log(a) } test() // -> 1 is printed test(null) // -> null is printed test(undefined) // -> 1 is printed
- nawgz 6y ago?? catches any falsy value, so it is quite semantically different than default arguments, and also quite different from ||
- Dylan16807 6y agoDid you write that backwards? || checks for falsy, ?? checks for null/undefined
- Dylan16807 6y agoNot because. You could have sugar evaluated once, sugar evaluated each time, not-sugar evaluated once, or not-sugar evaluated each time.