Is there anyway that we can deal with falsy 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 simply declare it like
function isOldEnough(age = 18) { ... }
Is there anythning we can do in ES5 to avoid this issue?
There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context. JavaScript uses type conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops.
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
Could be further improved with checking if age is equal to or greater than zero etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With