Hey Guys, I am having a hard time trying to figure out the following issue. I´m pretty new to JS so please bear with me.
I am following a course and one of the exercises was to apply or knowledge of functions and if/else statements was to build a BMI calculator. My problem is, first, on the JS console from google chrome, my code looked like this, and it didn´t work (The error message I received was that “bmi was not defined”).
[code]function bmiCalculator (weight, height) {
var bmi = (weight/(Math.pow(height,2)));
return bmi;
}if (bmi < 18.5){
alert(“Your BMI is ” + bmi + ” , so you are underweight.”);
}
if (bmi > 18.5 && bmi < 24.9){
alert(“Your BMI is ” + bmi + ” , so you have a normal weight.”);
}
if (bmi > 24.9){
alert(“Your BMI is ” + bmi + ” , so you are overweight.”)
}
bmiCalculator(98, 1.70);
[/code]
Like this, the function doesn´t work, so I blindly tweaked it to this, and now it works again. I want to understand why. Can someone please explain that to me? I have lots of problems with the JS console, and sometimes I have written the same code as my instructor and still things don´t work. What´s the cause of this? Is this why everyone hates JS? Thanks a lot guys!
This is the code that WORKS
[code]function bmiCalculator (weight, height) {
bmi = (weight/(Math.pow(height,2)));
return bmi;
}
bmiCalculator(98, 1.70);
if (bmi < 18.5){
alert(“Your BMI is ” + bmi + ” , so you are underweight.”);
}
if (bmi > 18.5 && bmi < 24.9){
alert(“Your BMI is ” + bmi + ” , so you have a normal weight.”);
}
if (bmi > 24.9){
alert(“Your BMI is ” + bmi + ” , so you are overweight.”)
}
The only changes I did was removing the “var” (which for me doesn´t make sense! since you have to write “var” the first time you define a variable, right?” and calling the function BEFORE the if statements. Is this entirely necessary?
Also I noticed, when running the first function (reverting the changes that I did of removing “var” and calling the function right after defining it) It now suddenly ALSO works, like the console saves the information somehow. Can someone please, please help me? I feel so lost, evern if the code works I need to understand why this happens!
Thankyou so much.
Edited by site staff: Inserted code tags.