How to avoid errors when assigning false values ​​to default values?

In any case, we can deal with falsity values ​​in || operators that are lazily evaluated?

So, for example, if we have:

function isOldEnough(age) { age = age || 18; return age; } isOldEnough(0) // returns 18 because 0 is falsy 

In ES6, you can just declare it as

 function isOldEnough(age = 18) { ... } 

Is there anything we can do in ES5 to avoid this problem?

+6
source share
1 answer

Something like (if I understood correctly):

 function isOldEnough(age) { var age = typeof age === "number" ? arguments[0] : 18; return age; } isOldEnough(null) // returns 18 isOldEnough("") // returns 18 isOldEnough(undefined) // returns 18 isOldEnough(0) // returns 0 

Can be further improved by checking if age is equal to or greater than zero, etc.

+3
source

All Articles