Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why {} != ( {} ) in JavaScript?

Tags:

javascript

It's commonly known that {} is shorter way to define an object like [] is for an array.

But now I am wondering why:

{} != ({})
  • {} evaluates to undefined
  • ({}) evaluates to "correct" Object

Why is JavaScript behaving like this ?

For example 1 equals to (1), so why {} not equals to ({}) ?

like image 259
Zaffy Avatar asked Jan 02 '13 01:01

Zaffy


People also ask

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

Each object, each {} is distinct. Same applies to arrays, too. Show activity on this post. 2) it does not make any difference whether you use == or === for comparing objects, because comparing them always returns false.

What does {} In JavaScript mean?

google doesn't have value (undefined, null) then use {} . It is a way of assigning a default value to a variable in JavaScript. Follow this answer to receive notifications.

Is != Same as =!?

The != operator is an equality operator that is used to check whether two operands are equal or not. The =! operator is a combination of two operators, one is an assignment, and the second is a negation operator that works on boolean value.

What is !== In typescript?

The !== operator returns true when elements are not equal value or not equal type.


1 Answers

{} != ({})

This is a syntax error.

SyntaxError: Unexpected token !=

{} is ambigious like that. Is it an empty block, or an empty object literal? It's failing because a comparison operator can not follow a block.

Wrapping it with parenthesis makes the parser treat it as an expression. An expression can't contain a block, so it knows it's an object.

However, if you wrap that comparison in an expression...

({} != ({}))

...it's still true because variables which have an object assigned to them's values are a pointer to them and as a consequence, they are never copied around by their contents (though this is irrelevant to your example). Because of this, their pointer is always different and the comparison fails.

This also implies that comparing two variables which point to the same object will work as expected, as their pointers will be the same.

like image 179
alex Avatar answered Oct 29 '22 12:10

alex