Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85565

type coercion between string and number

I'm little confused with my NOOP question here:

If a string and a number are compared, the string will be cast to an integer:

"1"==1 //true

Operating with string and a number, the number will be cast to a string:

"1"+1 // '11"

Why there is so difference in javascript between type coercion?

Upvotes: 0

Views: 96

Answers (1)

Felix Kling
Felix Kling

Reputation: 816590

That's just how the operators are defined (http://es5.github.io/#x11.9.3, http://es5.github.io/#x11.6.1).

  • With ==, if one operand is a string and the other is a number, the string is converted to a number.
  • With +, if one operand is a string, the other one is converted to a string.

So the difference is which operand is converted to which type, which is different for each operand (e.g. with multiplication, both operands are converted to numbers).

Upvotes: 3

Related Questions