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

一个人想着一个人 提交于 2019-12-05 04:19:08

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

I tested on safari this is not true.

null is primitive variable and null can be on left side.

But {} for javaScript is namespace. Used for creating global object.

Answer is simple: there is no sense for using {} with equality operators.

Updated :

It is a so clear :

Anything in javascript what comes with { have no assignment .

Let try to say :

{ x : null }

and what you will get ?

Nothing . Can you access this object again ? No.

console.log( null == {} );

console.log( {} == null );

console.log( null === {} );

console.log( {} === null );

// Also 

var object1 = {'key': 'value'}
var object2 = {'key': 'value'};
console.log(object1 === object2); //false

console.log({} === {}); //false

console.log({} == {}); //false

({}) == null; // little hack ;) false

// {} == null; syntax error !

 (typeof {}) == (typeof {});
 
 var A = {};
 var B = {};
 (typeof A) === (typeof B);

// console.log( (A instanceof "object" ) );
console.log( typeof A );

// This is only correct 
console.log(typeof A === typeof B)
console.log(typeof {} === typeof {})

I try this stupid thing :

{'test':0}.hasOwnProperty('test')

and i get same staff ( syntaxError ) . Don't use it like that!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!