So I’m learning JS, regarding functions and the use of return. Is there a functional difference between these 2 functions? They are both supposed to be BMI calculators. I’ve tested them out, and the first one works once you call the function and set a weight/height.
1.)
function bmiCalculator(weight, height){
return bmi = Math.round(weight / Math.pow(height, 2));
}
2.)
function bmiCalculator(weight, height){
var bmi = Math.round(weight / Math.pow(height, 2));
return bmi;
}
1.) works once I call function:
bmiCalculator(65, 1.8);
shows 20 on console
2.) works once I code:
var bmi = bmiCalculator(65, 1.8);
console.log(bmi);
shows 20 on console
4
Answers
The two functions are equivalent, and also equivalent to:
The
bmi
variable is not needed since you never refer to it after thereturn
statement.The console shows the same result in both cases because it automatically logs the return value of any expression you type.
Both works fine,based on convince you can used either of any, but according to industry standard 2nd approach is best i.e.,
}
Although, you must use let or const instead of var, benefits in scope control.
The two functions are not equivalent (just looking at them standalone), and the first will break in strict-mode (that also includes within es modules and classes), see the error below:
That’s because outside of strict-mode code, doing
return bmi =
will create a newbmi
variable in the global scope and return the value you just assigned (ie: the value to the right-hand side of the=
). This behaviour of creating "implicit globals" can cause hard-to-debug bugs so it’s not recommended and one of the reasons why strict-mode doesn’t allow it.Your second approach is the correct way to go. The
var bmi =
declares the variablebmi
to be local to yourbmiCalculator()
. Now your function is no longer creating/updating an implicit globalbmi
variable. Instead, it’s up to calling code of the function to decide what to do with it, whether that’s to assign it to a globalbmi
variable, a local variable, or use it in some sort of expression. The main thing is, no implicit global variables are being created in your code anymore with this approach.First function:
This one does the math to find the BMI, but it also does something else which can be confusing, especially for stricter rules in programming. So, it’s like making a cake but also trying to wear your shoes at the same time, which might cause some problems.
Second function:
This one is simpler. It calculates the BMI, puts it in a box (which is like the var bmi part), and then gives you the box with the BMI inside it. It’s like making a cake, putting it in a box, and then giving you the box. This way is easier to understand and follow the rules.