Why does JavaScript evaluate plus with a string and integers differently depending on the place of the string?
An example:
console.log("1" + 2 + 3);
console.log(2 + 5 + "8");
The first line prints 123 and the second prints 78.
When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false . When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.
In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place. In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a number(10).
In JavaScript when the + operator is used with strings, it concatenates them. This is why console. log("5"+1) returns "51". 1 is converted to a string and then, "5" + "1" are concatenated together.
Pass each string to the Number object to convert it to a number. Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.
The expression is evaluated left to right and therefore:
"1" + 2 + 3 -> "12" + 3 -> "123"
2 + 5 + "8" -> 7 + "8" -> "78"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With