Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0 === {} okay, but {} === 0 throws an error? [duplicate]

Tags:

javascript

I put the following into the browser console:

0 === {} // false
{} === 0 // SyntaxError: expected expression, got '==='

Why is this?

like image 935
Jack M Avatar asked Apr 11 '18 16:04

Jack M


People also ask

Why {} === {} is false in JavaScript?

javascript compares objects by identity, not value. Each object, each {} is distinct.

Why [] === [] is false?

Because [] creates a new array, so you are comparing one array object with another array object. It's not the contents of the arrays that is compared, the object references are compared. They are not equal because it's not the same object instance.

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

Why is this undefined in strict mode?

In strict mode, it is now undefined . When a function was called with call or apply , if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null ). In strict mode, the value is passed directly without conversion or replacement.


1 Answers

{} === 0 here {} is block statement not object literal.

But if you do say var a = {} === 0 it would work

var a = {} === 0

console.log(a);
like image 181
Yury Tarabanko Avatar answered Oct 18 '22 04:10

Yury Tarabanko