JAVASCRIPT IS NOT ADDING NUMBERS. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

JAVASCRIPT IS NOT ADDING NUMBERS.

I am having trouble with javascript, and i need help. If i add a number, using return statement is does not work, it will just add the numbers like 12 + 12, it will give me output 1212. But if i use other maths operators, it is working. See what i have do: function maTH(first_Num, second_Num){ return first_Num + second_Num; } document.write(maTH(prompt("Input First Number"), prompt("Input Second Number")));

7th Oct 2020, 6:29 PM
R£∆L ∆LILI
R£∆L ∆LILI - avatar
3 Answers
+ 4
When you say prompt() it returns a string by default, so 12+12 is added like a string. You must cast the value to a number type and you can either use Number(prompt()) or parseInt(prompt()). Strings see '+' as concatenating operator. And just like Abhay mentioned, the string with just numeric values are implicitly converted to numbers and the operation is performed on them.
7th Oct 2020, 6:35 PM
Avinesh
Avinesh - avatar
+ 3
Thank you for your help. It works. If to say i have the chance to mark many as the best answers, i could have mark all, because it works. But even thought, it is like i have marked all. Thanks🙋🙋🙋🙋
8th Oct 2020, 5:16 AM
R£∆L ∆LILI
R£∆L ∆LILI - avatar
+ 2
prompt returns a string ,using + on two strings concatenates them ,when using other operator ,they are implicitly converted to numbers
7th Oct 2020, 6:36 PM
Abhay
Abhay - avatar