Add numbers in prompt box

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Add numbers in prompt box



I would like to ask two questions where the user puts in a number, and then the computer adds the two numbers togheter. But when i run this code it only combines them like a string, and does not add.



This is my code:








4 Answers
4



You should put brackets around the a + b so that JS knows to evaluate that expression first.


a + b



document.write("Prisen for varene dine ble " + (a + b) + "kr.");


document.write("Prisen for varene dine ble " + (a + b) + "kr.");



This way it will evaluate the numeric expression of a + b first and concatenate that number with the string. Without the brackets the code will look left to right and see you are combining a string with a number, and so just concatenate them normally, and then again for the variable b.


a + b



You can add brackets around your output to specify that it is an addition operation (not conatenation):



document.write("Prisen for varene dine ble " + (a + b) + "kr.");


document.write("Prisen for varene dine ble " + (a + b) + "kr.");



your "+" operator in document.write() doesn't add two variables with each other. It has another meaning in that function.





I see! what do i use instead?
– Maria.A
2 mins ago



In JS, when you use the + operator between a number and a string, it will always convert the numbers to strings and do string concatenation. This is actually what you want here, you just need to enclose the sum in parentheses to make sure the sum is treated as being between two numbers:


+


document.write("Prisen for varene dine ble " + (a + b) + "kr.");






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard