2

Why does the + operator consider the number as string when added

Ex :

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Vinay
  • 79
  • 8

4 Answers4

4

When using + with 2 numbers: Math.

When using + with a string: Concatenation.

3 + 4 = 7
7 + '5' = '75'
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
2

+ will only add two numbers if it has a number on the left hand side and a number on the right hand side.

'3' + 4 + 5;

First '3' + 4 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

Second '34' + 5 has a string on the left hand side. So it converts the right hand side to a string and concatenates them.

3 + 4 + '5';

First 3 + 4 has a number on both sides, so it adds them. Second 7 + '5' has a string on the right hand side, so it converts the left hand side to a string and concatenates them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

It's simple rule in javascript :

string + number = string (operation work as a string)
'3' + 4 + 5; = 345
7 + '5' = 75
number + number = number (operation work as a number)
3 + 4 = 7
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
0

Regarding the "why", you've already gotten answers, the way to fix it, in case you don't know or if it can help somebody else:

var x = parseInt('3') + 4 + 5;
Kevin Chacón
  • 175
  • 12