+ 7

It is resulting as string . Like 4+2=42 . How to make it 4+2=6.

when I changed the code to ask for input, instead of returning 42 it'd return 402. (or instead of 1+1=2 it'd return 1+1=11) var a = prompt(); var b = prompt(); function addNumbers(a, b) { var c = a+b; return c; } document.write( addNumbers(a, b) );

7th Mar 2022, 7:26 AM
makhrab dip
8 Antworten
+ 6
var c = Number(a)+Number(b);
7th Mar 2022, 7:31 AM
Simba
Simba - avatar
+ 7
Additionally, Number() returns NaN (Not a Number) when either <a> or <b> as its argument were not convertible to a number. It might worth to consider checking that neither Number( a ) nor Number( b ) was NaN, before adding the two. a = Number( a ); b = Number( b ); if( !isNaN( a ) && !isNaN( b ) ) { return a + b; } return 0;
7th Mar 2022, 7:43 AM
Ipang
+ 2
makhrab dip When you takes user input it returns as a string so 4 and 2 are string. try this: var a = prompt(); console.log(typeof a) so either you can write Number(prompt()) or you can write parseInt(prompt(), 10) var a = parseInt(prompt(), 10); var b = parseInt(prompt(), 10); console.log(a + b);
7th Mar 2022, 9:07 AM
A͢J
A͢J - avatar
+ 1
You can also convert to a number by using the following... var c = parseInt(a) + parseInt (b);
8th Mar 2022, 7:03 PM
Ikenna Eze
+ 1
var a = prompt(); var b = prompt(); var c = +a + +b; document.write(c); If you prepend var a and b with + sign this will work also.
8th Mar 2022, 11:56 PM
{Carl}
{Carl} - avatar
0
By default the input are string. So they are just concatenated when added. Convert them to numbers to add. return Number(a) + Number(b)
7th Mar 2022, 1:58 PM
Aldrin Saurov Sarker
Aldrin Saurov Sarker - avatar
0
Use TryParse to check for int then add.
8th Mar 2022, 9:52 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
Var c = prompt(a+b)
9th Mar 2022, 6:30 AM
Deepak Singh