Odd behaviour of comparison of object literals

后端 未结 4 1545
有刺的猬
有刺的猬 2020-12-10 22:24

I have searched but could not find logic behind following in JavaScript.

When I type in the Chrome console:

{} == null 

it returns

4条回答
  •  甜味超标
    2020-12-10 22:38

    I assume you understand why {} == null throws SyntaxError. Long story short it is because { in the begining starting a block statement not an object literal. You could check the answer here

    As of why {} == {} this works.

    If you check chromium code that evaluates expressions in console. You could find the following (code)

    if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
        text = '(' + text + ')';
    executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);
    

    This code wraps {} == {} code with parentheses making it a valid expression ({} == {}) comparing two empty object literals. Which evaluates to false because objects are compared by reference.

    Node repl has the same behaviour src

    if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) {
      // It's confusing for `{ a : 1 }` to be interpreted as a block
      // statement rather than an object literal.  So, we first try
      // to wrap it in parentheses, so that it will be interpreted as
      // an expression.
      code = `(${code.trim()})\n`;
      wrappedCmd = true;
    }
    

提交回复
热议问题