-1

Hey could you please tell me why this happens when I add

var a = 3
var b = "2"
console.log(a + b ) // 32

the above output is right But when I do subtraction then it shows

console.log(a - b ) // 1

and it is the same for multiplication (o/p:- 6) and when I divide the output is (1.5) why this is happing when I do other arithmetic operations except for addition.

PRADEEP GORULE
  • 159
  • 1
  • 11

2 Answers2

0

The '+' operator when operated on string does concatenation. The 'b' variable is a string literal and thats why you are getting output '32'.

IRSHAD
  • 1,582
  • 11
  • 16
0

The + operator is pecial in this sense. It will add numbers, but concatenate if it encounters a string.

However, a behavior like this makes no sense for other operators.

For example, what do you expect "foo" - 2 to do? And "foo" / 3? Divide "foo" into 3 parts? Then what about 3 / "foo"?

So, the general rule is rather that arithmetic operators always coerce their arguments to numbers, and the addition / concatenation operator(+) is the only exception.


Actually, the comparison operators (<, <=, >, >=) can also work on strings, but those aren't arithmetic operators.

FZs
  • 16,581
  • 13
  • 41
  • 50