I don't quite understand why the if
statement evaluates true
but the console.log
comparison does not.
I double checked the MDN documentation and they say {}
is a truthy value. So why does my console.log
statement disagree?
I did try, as a last ditch, using ==
instead of ===
.
var test = {};
console.log(test);
console.log(test === true);
console.log({} === true);
if ({}) {
console.log('What the ?');
}
===
is not the way to check whether a value is truthy in the way you are checking.
For example, all the following are truthy. But if you try to do ===
with true
they will result in false
other than the truthy value true
if (true)
if ({})
if ([])
if (42)
if ("foo")
if (new Date())
if (-42)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
console.log(true === true);
console.log({} === true);
console.log([] === true);
console.log(42 === true);
console.log("foo" === true);
console.log((new Date()) === true);
console.log(-42 === true);
console.log(3.14 === true);
console.log(-3.14 === true);
console.log(Infinity === true);
console.log(-Infinity === true);
You can check truthy by using !!value
. For example
var test = {};
console.log(!!test === true);
Similarly we can check for all the truthy above as following:
console.log(!!true === true);
console.log(!!{} === true);
console.log(!![] === true);
console.log(!!42 === true);
console.log(!!"foo" === true);
console.log(!!(new Date()) === true);
console.log(!!-42 === true);
console.log(!!3.14 === true);
console.log(!!-3.14 === true);
console.log(!!Infinity === true);
console.log(!!-Infinity === true);
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