Javascript string and numeric variables
What evaluates the following?
"1"+2+4
How about this:
5 + 4 + "3"
In the first case, since it "1"
is a string, everything is a string, hence the result "124"
. In the second case, his 93
. What's going on here? Why does addition occur in one instance while string concatenation occurs in another?
var x = "1" + 2 + 4;
var z = 5 + 4 + "3";
console.log(x); // "124"
console.log(z); // 93
Can anyone explain this?
evaluated from left to right.
"1"+2+3
^--^
"12" //string +3
^_____________^
"123" //string
in the second case
1+2+"3"
^_^
3+"3"
^___^
"33" // string
Think of the order of operation (rtl or ltr) each time it does a binary operation that converts it accordingly, so 5 + 4 will be int and (5 + 4) + "3" will be a string because "3" is a string
The same technique applies to different examples
var x = "1" + 2 + 4; // 124
This takes line "1" and concatenates lines "2" and "4" into it.
var z = 5 + 4 + "3"; // 93
This takes the numbers 4 and 5 and adds them together to get the number 9, and then concatenates the string "3" to create another string.
The key point to remove is that the end result of what you are doing here is string concatenation. The order in which the numbers are evaluated is different, but the end result is a string.
In the first case, you create a string first (1) and then javascript concatenates the next number as strings (124).
In the second case, you first create a number, then javascript adds a second number to that first number (5 + 4 = 9) and then you add a string so that it does the concatenation of 9 and 3
In both cases, type conversion and left-to-right precedence are applied. In the first,
var x = "1" + 2 + 4; // 124
the compiler accepts 1 as a string and after that it will concatenate with 2, now 12 is a string, so it will be concatenated with 4 and the result will generate "124" as a string.
var z = 5 + 4 + "3"; // 93
in the second, the first 5 and 4 are numeric, so do the addition and the result will be 9. and it will be concatenated with string 3, the soo output will be 93 as string.