Search code examples
javascriptimplicit-conversiondynamic-typing

why + sign is the exception in javascript?


i did this

> 5 + 2 // 7, this is correct 

> 5 - 2 // 3 , obviously 

> 5 - "2" // 3 , ohh, that's awesome 

> 5 % "2" // 1 , :)

> 5 / "2" // 2.5,looks like 2 is automatically converted to integer.Perfect!

> 5 + "2" // "52" Really? 

Certainty, something extra is going on with plus sign. What's that and why ?


Solution

  • As per the ECMA 5.1 Standard Specification for Binary + operator,

    7. If Type(lprim) is String or Type(rprim) is String, then
          Return the String that is the result of concatenating ToString(lprim)
          followed by ToString(rprim)
    

    So, if either of the operands are of type String, then the standard mandates the implementations to convert both the operands to string type and concatenate them.

    Note: But the unary + operator behaves differently with strings. It converts the strings to numbers.

    1. Let expr be the result of evaluating UnaryExpression.
    2. Return ToNumber(GetValue(expr)).