Return Ends the Function
return does two things at once: it gives a value back, and it ends the function immediately. The rest of the function doesn't run:
function add(a, b) {
return a + b;
console.log("This line never runs.");
}
console.log(add(2, 3));This prints:
5The line after return never runs, because the function ended one line earlier.
This is handy together with conditions. The following function describes the weather based on the temperature:
function describeWeather(degrees) {
if (degrees < 0) {
return "freezing";
}
if (degrees < 20) {
return "cool";
}
return "warm";
}
console.log(describeWeather(-5));
console.log(describeWeather(12));
console.log(describeWeather(25));This prints:
freezing
cool
warmLet's follow the three calls:
describeWeather(-5):-5 < 0istrue, so the function returns"freezing"and ends. The second condition is never checked.describeWeather(12): the first condition isfalseand the second one istrue, so the function returns"cool".describeWeather(25): neither condition istrue, so the function gets all the way to the last line and returns"warm".
We didn't need any else: once a return runs, the rest of the function is skipped anyway. But the order of the conditions matters, because the first return that runs wins. If the function checked degrees < 20 first, it would return "cool" for -5, since -5 is less than 20 too.
Instructions
- 1
Complete the function
ticketPrice, which returns the price of a zoo ticket for a visitor of the given age: children under 6 go free (0), visitors under 18 pay5, and everyone else pays10. The program then prints0,5and10. - 2
Seniors aged 65 and over pay
5too. Add a condition for them to the function, and at the end of the program, printticketPrice(70).