Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does commuting the arguments of == in a console change the output?

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:

enter image description here

  • Why does this happen?
  • Why does this only happen in a console and not when the browser executes a script within an HTML page?

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?

like image 335
Paul Benn Avatar asked Jun 22 '18 11:06

Paul Benn


1 Answers

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

like image 176
Inus Saha Avatar answered Sep 28 '22 09:09

Inus Saha