4
{} == []

outputs:

Uncaught SyntaxError: Unexpected token ==

wheres,

{} == {}

outputs

false

Sagar Bahadur Tamang
  • 2,670
  • 2
  • 24
  • 41
King
  • 49
  • 1

2 Answers2

1

Apparently, this is an example of "sticking to your first thought"!

Last edit:
If you use { in the beginning of a line or after a closed statement, the JavaScript emulator will see this curly-bracked as the beginning of a code block. Therefore will the emulator see } as the closing of that block. this means that == [] is standing alone in the middle of your code...

Wrapping it into round brackets, the emulator will translate it to an if-statement and then the { will be treated as the opening of an in-the-fly-object.

eg:

({} == []) // => false

Edit:

After some quick research, it seems that it is a rare case where the emulator fails.

Using Chrome 71:

If you type in the console var a = {} the output is {}. So a variable a is created, an empty object is created an stored into a.

But if you type var b = [] the output is undefined. Here the emulator is messing up, because if you type b, the output is []. It means that the variable b is created, an object of type array is created and stored into b. But the return object of the array creation using the array literal is undefined.

Further testing shows me that {} == function() will throw the same error: Uncaught SyntaxError: Unexpected token ==.
This make me think that using the array literal ([]) will returns a function that creates the array.

var b = [] // => literal returns a function that will be executed immediately
{} == b // => false because b holds the result of the executed literal-function.


{} == function() // throws error
{} == [] // throws error
var f = function() { --some code-- }
{} == f // throws error

rahul
  • 7,573
  • 7
  • 39
  • 53
Stef Geysels
  • 1,023
  • 11
  • 27
0

This happens because {} isn't interpreted as an empty object, but as an empty block.

The curly brackets use, in javascript, is ambiguous. It can be used both to define objects and to define blocks.

For example, the following block won't give you any error, because it's just a legal code block:

{
  console.log('hello world!');
}

So when you type {} == [] you are comparing an empty block with an empty array, and it makes no sense.

When you type {} == {}, instead, the parser understands that you are comparing two objects and it returns false.

I guess this happens only because of the implementation and not because of specifications

  • How do you distinguish whether it is a block or an object? However, both expressions will be reported in the Firefox browser. – King May 06 '19 at 02:19
  • You can find an answer in the linked question: https://stackoverflow.com/questions/26347326/when-does-js-interpret-as-an-empty-block-instead-of-an-empty-object – Christian Vincenzo Traina May 06 '19 at 07:58