Returning Values

The function printArea you wrote a moment ago prints the area, and that's all. But what if we want to keep calculating with the result, for example add up the areas of all the rooms in an apartment? A printed value is only shown in the console; the program can't work with it anymore.

That's why functions can return a value. The keyword return sends a value back to the place where the function was called:

function add(a, b) {
    return a + b;
}

const sum = add(2, 3);
console.log(sum);

This prints:

5

The call add(2, 3) runs the function, and the function returns 5. You can imagine that JavaScript replaces the call with the value the function returned, so const sum = add(2, 3); becomes const sum = 5;. The value a function returns is called its return value.

You can use a call anywhere you would write a value: print it straight away, or calculate with it:

function add(a, b) {
    return a + b;
}

console.log(add(2, 3));
const total = add(2, 3) * 2;
console.log(total);

This prints:

5
10

In console.log(add(2, 3)), JavaScript first calls add(2, 3), and then prints the 5 the function returned. In add(2, 3) * 2, the call becomes 5, and 5 * 2 is 10.

Beginners often mix up return and console.log. console.log only shows a value to you, in the console. return gives the value to the program, which can store it, calculate with it or print it. Look at what happens when a function prints its result instead of returning it:

function printSum(a, b) {
    console.log(a + b);
}

const result = printSum(2, 3);
console.log(result);

This prints:

5
undefined

The 5 was printed by the console.log inside the function. But the function didn't return anything, and a function without return returns undefined. So result is undefined. That's why most functions return their result, and the code that calls them decides what to do with it.

Instructions

Complete the function rectangleArea so that it returns width * height. The program then prints Kitchen: 12 and Bedroom: 20.

The apartment also has a living room of 6 × 5 meters. Create a variable livingRoom with its area, calculated with the function rectangleArea. Then print the area of the whole apartment, kitchen + bedroom + livingRoom, with the label "Whole apartment:". It should be 62.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

5/10

Next