Day 5: Functions Part 1
Lesson 5: Multiple Inputs
Let's take our last example and make it more useful, make the editor side of the playground wider so you can see this all clearly:
JavaScript function arguments are positional. That means that the position of what we pass in matters. In this case we must pass in the measurement we want to convert first and then the unit of that measurement second.
If we swap them around it will break the code and not work. Also, we have declared the function as taking two arguments, so we must give it two arguments.
There is an improvement we can make here that demonstrates another important part about functions in JavaScript.
A function will only return once. So in the above if unit === 'cm'
is true, then the function will return
and no more code will execute. This means we don't need the else statement here, and we can do this instead:
1function convertMeasurement(measurement, unit) { 2 if (unit === "cm") { 3 return measurement / 2.54; 4 } 5 return measurement * 2.54; 6}
Change the convertMeasurement
function code to match this and see how it still works the same.
A function can have multiple return statements BUT the first one that it hits and runs will end that function's execution and return
Even though we are returning a value from this function we don't have to do anything with it, so this code is perfectly valid:
1function convertMeasurement(measurement, unit) { 2 if (unit === "cm") { 3 return measurement / 2.54; 4 } 5 return measurement * 2.54; 6} 7 8convertMeasurement(400, "cm");
It's a bit pointless in this case because the whole point of the convertMeasurement
function is to return a converted unit, it doesn't matter that we don't assign the function's return to anything.
So we can input multiple values, what about returning them?