Why the output is 33 not 6? | SoloLearn: Learn to code for FREE!

+7

Why the output is 33 not 6?

When Sum button is clicked, alert Window will appear. https://code.sololearn.com/WuTa4N7pOT71/?ref=app

12/27/2018 4:43:37 AM

Muhd Khairul Amirin Bin Yaacob

25 Answers

New Answer

+4

https://code.sololearn.com/W0uk4VD12ALx/?ref=app

+4

Best way to debug this code is checking type of things you are adding. Add following code to your function console.log(typeof(a)); console.log(typeof(b)); This tells a and b are string so they concatenate. So you are actually doing this "3"+"3"=33. Solution: coerce (change to another data type) those two inputs that are initially string type into number type by using parseInt() function.

+4

Because you added it.

+3

Try var sum=+a+ +b;

+3

Thanks everyone😄

+3

best practice in JS is still parseInt see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt

+3

Looks like someone had downvoted this questions as well as its answers. 😓

+3

You need to convert a and b to numbers otherwise you're just concatenating two strings together.

+3

The value is retrieved as a string that's why

+2

Calvin is it really good practice using that?

+2

The Learner the reason why your code has an error is caused when you try to add a 'addEventListener' method to the input tag with id 'cal'. When you do this the input tag with id 'cal' doesn't exist yet, the body hasn't loaded it and it's children, but your javascript is trying to get the values regardless and so null is returned for the variable cal. What you should do is run the javascript after all the elements that you need in the html have loaded. <body onload="onloadMethod();"> </body> function onloadMethod(){ Initialise all variables in here }

+2

♣Dave♠David♣ Yeah at least I'm gonna see the result with that ... thanks for help though 😄

+2

The Learner Ive fixed some of your bug. https://code.sololearn.com/WKdwfdR885Pw/?ref=app

+2

ShortCode 😊 thank you

+1

Hahaha funny tricky fact about input type ="number", they are still string

+1

If you wanna prevent user to use letter or any other character but not a number you can use the isNaN function, I found it useful with my code: https://code.sololearn.com/WnLYR0lI6Ez6/?ref=app Note: if somebody sees my code plz tell me why is showing me that error !! :)

+1

♣Dave♠David♣ but why in my computer works? edited: not SL but in my local or if I open it in a browser.

+1

The Learner i'm sorry i don't understand

+1

♣Dave♠David♣ well ... I created the code in my computer but not directly in Sololearn ... I created in brackets text editor, the page resulted ok everything. working.. but two days ago I uploaded to SL and it shows me that error ....

+1

Remove value=3 in both places and run the code