Javascript function doesn't add a variable to a number for some reason! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Javascript function doesn't add a variable to a number for some reason!

I wrote this function that displays the opposite magnetic heading in degrees. But instead of completing the addition it instead just add these two together as if they were strings. function opp_head(x){ if(x<180){ x += 180; return x; } else { x -= 180; return x; } } let x = prompt("Enter your heading to get the opposite here!"); console.log(opp_head(x) + " is the opposite heading.");

11th Jan 2023, 6:42 PM
idk still me
idk still me - avatar
5 Answers
+ 2
Cast to a numeric type before using the x with parseInt(). After that you can use it as a number: let x = parseInt(prompt("Enter your heading to get the opposite here!")); Also, with ECMASCRIPT 6 you can do interpolation using backticks to print your answer, it's something like this: console.log(`${opp_head(x)} is the opoosite heading.`)
11th Jan 2023, 6:59 PM
Edgar Sabido
Edgar Sabido - avatar
+ 2
parseInt(x) before passing x to the function will make x a number
11th Jan 2023, 6:51 PM
Lisa
Lisa - avatar
0
You need to convert the value of x to a number before adding 180 to it. You can do this using the Number() function.
11th Jan 2023, 9:15 PM
Aditya Dixit
0
function opp_head(x){ x = Number(x); if(x<180){ x += 180; return x; } else { x -= 180; return x; } } let x = prompt("Enter your heading to get the opposite here!"); console.log(opp_head(x) + " is the opposite heading.");
11th Jan 2023, 9:16 PM
Aditya Dixit
0
Add a parseFloat(x) instead of Number (x) or parseInt(x) and if you are also getting your values from an input tag use . valueAsNumber instead of.value
13th Jan 2023, 2:15 PM
Chinedu Gabriel
Chinedu Gabriel - avatar