Adding two numbers concatenates them instead of calculating the sum

okconfused picture okconfused · Jan 24, 2013 · Viewed 569k times · Source

I am adding two numbers, but I don't get a correct value.

For example, doing 1 + 2 returns 12 and not 3

What am I doing wrong in this code?

Answer

elclanrs picture elclanrs · Jan 24, 2013

They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:

var x = +y + +z;