If I open my browser console (tested in Chrome/Firefox) and type:
null == {}
I get:
false
However, if I commute both arguments to the ==
operator and instead type:
{} == null
I get:
Uncaught SyntaxError: Unexpected token ==
Image:
EDIT:
While question 35812626 addresses this and explains the cause as JS parsing the {}
as a code block, it uses the triple equals (strict comparison) operator ===
, not the double equals ==
. As a user points out below, a code block can definitely be followed by ==
without causing a syntax error:
{} == {} // false
How come this works and my example does not?
I think its because the interpreter interprets {}
as a block of code not as an object.
so your code {} == null
turns out to be a block start and end then a statement starts with ==
which is definitely a syntax error.
but if you can try ({} == null)
I think it should run fine.
and as pointed out by @dhaker {}=={}
returning false
not an error.
and i found there are few scenario returning result and few getting error.
following are getting error:
{}==null //Uncaught SyntaxError: Unexpected token ==
{}==1 //Uncaught SyntaxError: Unexpected token ==
{}==0 //Uncaught SyntaxError: Unexpected token ==
{}==true //Uncaught SyntaxError: Unexpected token ==
{}==false //Uncaught SyntaxError: Unexpected token ==
{}==true //Uncaught SyntaxError: Unexpected token ==
{}=='' //Uncaught SyntaxError: Unexpected token ==
{}=='hi' //Uncaught SyntaxError: Unexpected token ==
{}==(new Object) //Uncaught SyntaxError: Unexpected token ==
following are returning result without an error:
{}=={} //false
{}==function(){} //false
so i guess it has something to do with how the Javascript is compiled or interpreted by the browsers.
for much detailed answer please check following answer.
Odd behaviour of comparison of object literals
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