+ 3
To get the right result, you need to cast the input from string to Number. see example below: var n1 = prompt("first number") var n2 = prompt("second number ") n1=Number(n1) n2=Number(n2) alert(n1+n2)
22nd Nov 2016, 10:24 PM
Rill Chritty
Rill Chritty - avatar
+ 3
Prompt always return a string. If you want to change string to expression use eval() var x = prompt("Num1"); var y = prompt("Num2"); document.write(eval(x +'+'+ y));
23rd Nov 2016, 12:56 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
In JavaScript the + symbol is used both for the addition of numbers and the concatanation of strings. JavaScript prior to performing the operation checks the two arguments of the plus operator and based on their type decides which version of the + operator will be executed. In particular we have three possible alternatives: 1. number + number -> addition 2. string + string -> concatanation 3. number + string or string + number -> concatanation. (In the third case JavaScript converts the number into its corresponding string literate and then proceeds with the concatanation)
22nd Nov 2016, 10:22 PM
Miltiadis Siavvas
0
var x = parseInt(prompt("Num1")); var y = parseInt(prompt("Num2")); document.write(x + y); Simple solution : prompt takes input as a string, so parse ( meaning : convert) it into an integer using parseInt( ) method.
18th Feb 2017, 1:52 AM
[No Name]
[No Name] - avatar