JavaScript confusion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

JavaScript confusion

Take a look at my codes, code called "Geometric Calculator [in progress]". I have the first function in JavaScript causing the problem. part of the function is: if(perimeterChecked()){ var result = 2 * (length + width); }else{ var result = length * width; } It checks if a check box is checked (works fine), but the calculation is messed up. I tried changing the calculation to length + width, and I realized it is being treated like a string. Why, and how can I fix that?

16th Mar 2017, 5:24 AM
David Koplik
David Koplik - avatar
8 Answers
+ 22
if(perimeterChecked()){ var result = 2 * (Number(length) + Number(width)); }else{ var result = length * width; }
16th Mar 2017, 5:33 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
well if your data is coming from an input, then it's systematically gonna be a string (even if it includes numbers only).
16th Mar 2017, 6:06 AM
CHMD
CHMD - avatar
+ 1
the + sign is also used for concatenation. if your variable are string, then JavaScript will perform a concatenation instead of an addition. to overcome this, you will have to convert your string to an integer. So if your string only contains numbers, you can use the unary + operator. ex +"10" + +"69" In your case, it would give something like that: +length + +width
16th Mar 2017, 6:00 AM
CHMD
CHMD - avatar
+ 1
KINGODX that's the answer I needed!! thanks! so it's string even if the input type is only number... okay :D
16th Mar 2017, 6:12 AM
David Koplik
David Koplik - avatar
0
Yeah, but why is it treated like a String? I mean it works if I do 2*(length*width), but if I put a plus sign, it gives me weird results... is it something with the plus sign??
16th Mar 2017, 5:40 AM
David Koplik
David Koplik - avatar
0
I know Java, I know HTML, and I don't need PHP for JavaScript. I was asking if you know what the cause is..
16th Mar 2017, 5:52 AM
David Koplik
David Koplik - avatar
0
KINGODX okay, but my expression doesn't contain ANY strings. So why is it doing that?
16th Mar 2017, 6:03 AM
David Koplik
David Koplik - avatar
- 4
to understand java script.. must study HTML,php, and java
16th Mar 2017, 5:48 AM
KRITESH OJHA
KRITESH OJHA - avatar