-1

When we subtract/multiply/divide a number with a number(type as string), it will treat both variable as number.

But when we add a number with a number(type as string), it will treat second var as string and concat the variables.

For example

var a = 4;
var b = "4";
var c;

c = a + b;
console.log(c)

c = a - b;
console.log(c)

c = a * b;
console.log(c)

c = a / b;
console.log(c)

Result output is

"44"

0

16

1

Why there is different behaviour for addition in javascript?

Community
  • 1
  • 1
  • [Check](https://stackoverflow.com/questions/16124032/js-strings-vs-concat-method) – Durga Nov 13 '17 at 07:40
  • This might be useful for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators – Fahad Nisar Nov 13 '17 at 07:41

3 Answers3

0

Because "+" ist not only an arithmetic operator but also the "string concatination operator".

In your first example you concatenate 2 strings.

In your other examples the string is coerced to a number and then the arithmetic operation is executed.

There are some steps to prevent this from happening:

var a = 4;
var b = "4";

c = +b + a // 8
console.log(c);
c = parseInt(b) + a // 8
console.log(c);
c = b*1 + a // 8
console.log(c);

You just have to make sure that both variables have the type number when you add them together.

Gaslan
  • 808
  • 1
  • 20
  • 27
Michael Filler
  • 328
  • 2
  • 12
0

This is because + operator is also used for string concatenation. You can use the + operator incase you want to convert in into a number

var a = 4;
var b = "4";
console.log(a + b);
console.log(a + +b);
marvel308
  • 10,288
  • 1
  • 21
  • 32
0

In JavaScript + operates both as ADD and string concatination. When you do a + b, a is implicitly coerced into a string. Whereas with other operators cannot be used on strings. Therefore a is implicitly coerced into number, so the math operation.

pmaddi
  • 449
  • 5
  • 18