Search code examples
javascriptprimitive

How does primitive value conversion happen in `1 + {}` and `{} + 1`?


I'm a beginner developer, and I can't understand why below statements have such outputs. Can someone explain that how/why following two expressions are interpenetrated by JavaScript differently, that their outputs are different.

1 + {} // => "1[object Object]"
{} + 1 // => 1

As + is a commutative operator so I was expecting same answer but it seems I am missing some language rules.


Solution

  • In JavaScript, the addition operator (+) adds the value of one numeric expression to another, or concatenates two strings.

    The types of the two expressions determine the behavior of the + operator.

    If both expressions are numeric or Boolean, then they are added.

    1 + 1;
    // 2
    
    true + false;
    // 1
    
    true + true;
    // 2
    

    If both expressions are strings, they are concatenated:

    "hel" + "lo";
    // "hello"
    

    If one expression is numeric and the other is a string they are also concatenated:

    1 + {}
    // "1[object Object]"
    

    Here [object Object] is the string representation of {}:

    String({})
    // "[object Object]"
    

    So hopefully the first example is clear.

    However, things get weird if the first operand of + is an empty object literal. JavaScript interprets this as an empty code block and ignores it.

    Hence, {} + 1 is simply interpreted as +1, which is obviously 1.

    So, why is the first {} interpreted as a code block? Because the complete input is parsed as a statement and curly braces at the beginning of a statement are interpreted as starting a code block.

    You can fix this by forcing the input to be parsed as an expression, which then gives you the output you would expect:

    ({} + 1)
    // "[object Object]1"
    

    You might alike to read this great post to find out more.