I was reading the re-introduction to JavaScript on MDN and in the section Numbers it said that you can convert a string to a number simply by adding a plus operator in front of it.
For example:
+"42" which would yield the number output of 42.
But further along in the section about Operators it says that by adding a string "something" to any number you can convert that number to a string. They also provide the following example which confused me:
"3" + 4 + 5 would presumably yield a string of 345 in the output, because numbers 4 and 5 would also be converted to strings.
However, wouldn't 3 + 4 + "5" yield a number of 12 instead of a string 75 as was stated in their example?
In this second example in the section about operators wouldn't the + operator which is standing in front of a string "5" convert that string into number 5 and then add everything up to equal 12?
In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.
If you add a number and a string, the result will be a string!
To concatenate two numbers in JavaScript, add an empty string to the numbers, e.g. "" + 1 + 2 . When using the addition operator with a string and a number, it concatenates the values and returns the result. Copied! We used the addition (+) operator to concat two numbers.
Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.
What you are talking about is a unary plus. It is different than the plus that is used with string concatenation or addition.
If you want to use a unary plus to convert and have it added to the previous value, you need to double up on it.
> 3 + 4 + "5" "75" > 3 + 4 + +"5" 12
Edit:
You need to learn about order of operations:
+
and -
have the same precedence and are associated to the left:
> 4 - 3 + 5 (4 - 3) + 5 1 + 5 6
+
associating to the left again:
> 3 + 4 + "5" (3 + 4) + "5" 7 + "5" 75
unary operators normally have stronger precedence than binary operators:
> 3 + 4 + +"5" (3 + 4) + (+"5") 7 + (+"5") 7 + 5 12
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