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

1.3k views Asked by At

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?

3

There are 3 answers

0
jherax On BEST ANSWER

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

0
Lightness Races in Orbit On

If you simply broke down the problem into its constituent parts and typed +" " into the console, you'd see that it evaluates to 0. And 1+3+0 is 4.

0
Sebastian Simon On

The following operations are done when the statement is evaluated:

1 // one
+ // add
+ " " // implicitly convert " " to a number (0)
+ // add
3 // three

So basically 1 + 0 + 3. There’s no string that enters this calculation. It’s converted to a number beforehand.

The + operator in this case is the unary + (see “coercion”).