Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript adding a string to a number

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?

like image 619
SineLaboreNihil Avatar asked May 13 '13 12:05

SineLaboreNihil


People also ask

What happens when you add a string and a number in JavaScript?

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.

What will be the result if you add a number and a string?

If you add a number and a string, the result will be a string!

How do you concatenate numbers in JavaScript?

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.

How do you do addition in JavaScript?

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.


1 Answers

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 
like image 111
epascarello Avatar answered Oct 12 '22 03:10

epascarello