I read that the double pipes in JavaScript check to see if a variable is falsy, and that undefined
is a falsy value in JavaScript, e.g.
It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.
So I tried this out and find that undefined indeed does not get evaluated as falsy but instead throws an error:
let elemContent = document.getElementById('content'); let a = null; let b = 2; elemContent.innerHTML += a || 'ok'; // "ok" elemContent.innerHTML += b || 'ok'; // "2" elemContent.innerHTML += whatever || 'ok'; // "ERROR: whatever is not defined"
http://jsfiddle.net/ueqo6yko
Is undefined
a falsy value in JavaScript or not, or how does one understand this contradiction?
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. The keyword false . The Number zero (so, also 0.0 , etc., and 0x0 ).
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 .
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
The 7 falsy values are: 0 , 0n , null , undefined , false , NaN , and "" .
Because in your code, whatever
is not only undefined
but furthermore not declared
To avoid this error, you could do the following:
let elemContent = document.getElementById('content'); let a = null; let b = 2; elemContent.innerHTML += a || 'ok'; // "ok" elemContent.innerHTML += b || 'ok'; // "2" elemContent.innerHTML += (typeof whatever !== 'undefined' && whatever) || 'ok3'; // "ok3"
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