Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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:

5

The 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
warm

Let's follow the three calls:

  • describeWeather(-5): -5 < 0 is true, so the function returns "freezing" and ends. The second condition is never checked.
  • describeWeather(12): the first condition is false and the second one is true, so the function returns "cool".
  • describeWeather(25): neither condition is true, 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. 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 pay 5, and everyone else pays 10. The program then prints 0, 5 and 10.

  2. 2

    Seniors aged 65 and over pay 5 too. Add a condition for them to the function, and at the end of the program, print ticketPrice(70).

Back

6/10

  1. 1. Defining Functions
  2. 2. Calling Functions
  3. 3. Parameters and Arguments
  4. 4. Default Parameter Values
  5. 5. Returning Values
  6. 6. Return Ends the Function
  7. 7. Variable Scope
  8. 8. Functions and Arrays
  9. 9. Arrow Functions
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.