Why does the +
operator consider the number as string when added
Ex :
'3' + 4 + 5; // "345"
3 + 4 + '5'; // "75"
Why does the +
operator consider the number as string when added
Ex :
'3' + 4 + 5; // "345"
3 + 4 + '5'; // "75"
When using +
with 2 numbers: Math.
When using +
with a string: Concatenation.
3 + 4 = 7
7 + '5' = '75'
+
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.
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
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;