Search code examples
javascriptarithmetic-expressions

console shows 6 when i multiply integer (3) into string ("2") in JavaScript


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.


Solution

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