+ 2

What's wrong in my code?

I made a very simple calculator using JavaScript, but the addition feature isn't working properly. For example, if I add 2+2 it shows 22 as result. Can anybody tell me the right way to do addition? I am a beginner in JavaScript. https://code.sololearn.com/W9FYG6CqR2bw/?ref=app https://code.sololearn.com/W9FYG6CqR2bw/?ref=app

2nd Apr 2020, 6:19 PM
Shahid Ali
Shahid Ali - avatar
6 odpowiedzi
+ 1
function add() { var first = Number(prompt("Enter the first number")); var second = Number(prompt("Enter the second number")); var result = first + second; document.write("The Answer is "+result); } Prompt take input as string type.. + is also used for cancatination of string.. There cancatination taking place because of string type. Convert to number.. For other operators, its taking implicit convertion..
2nd Apr 2020, 6:24 PM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 Thanks 🙏 Now it works ☺️
2nd Apr 2020, 6:30 PM
Shahid Ali
Shahid Ali - avatar
+ 2
3rd Apr 2020, 7:51 AM
Shahid Ali
Shahid Ali - avatar
+ 2
Mulla Aman Lalasahab Thanks bro for supporting, but my problem has already solved. Check the comments 😊😊
5th Apr 2020, 10:26 AM
Shahid Ali
Shahid Ali - avatar
+ 1
Shahid Ali Also alternatively, instead of Number function, you can use + as specified above, Ex: var x=prompt(" "); x= +x; Now x is converted to number type... Or var x= +prompt(""); You're Wel come...
2nd Apr 2020, 6:38 PM
Jayakrishna 🇮🇳
+ 1
var result = +first + +second;
2nd Apr 2020, 6:52 PM
Alexander Lebedev
Alexander Lebedev - avatar