Search code examples
javascriptconsole.logcoercion

Why javascript console.log(1 + + " " + 3); sentence returns 4 and not "1 3"?


When the statement console.log(1 + + " " + 3); is executed in the Chrome console, the result is 4 and not "1 3" as i would expect.

Can someone please explain why this is the case?


Solution

  • This behaviour is called coercion.

    In this case the unary plus operator + converts to number the expression at the right. If it cannot parse a particular value, it will evaluate to NaN.

    + " " //--> is coerced to 0
    

    You can see some coercion examples in this Gist: JavaScript Coercion