Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my empty object literal log as false?

Tags:

javascript

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 ?');
} 
like image 201
yohohosilver Avatar asked Jun 03 '18 22:06

yohohosilver


Video Answer


1 Answers

=== 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);
like image 133
Md Johirul Islam Avatar answered Oct 12 '22 22:10

Md Johirul Islam