Search code examples
javascriptnode.jsbrowserconsole.log

Object and number subtraction negates the number in browser js


Why does {} - 1 give -1 result in browser javascript?

As per my understanding of how type coercion works here, first valueOf() will be called on the {}, which is not a primitive value, so next toString() will be called, which gives [object Object]. That would give us '[object Object]' - 1, so NaN, however it actually results in -1.

In node this seems to work as per my understanding, as the result is NaN there.


Solution

  • In the console, for involved reasons, {} - 1 is evaluated as if you had typed

      {
        // no statements
      }
      -1;
    

    It's a block statement followed by the expression -1.

    If you type ({} - 1) to force evaluation as an expression, you get NaN.

    The console REPL is not simply an expression evaluator; it attempts to evaluate and run anything you type as a sequence of statements. A statement that starts with { is always disambiguated as being the start of a block of statements, never as an object initializer.