← All lessons/Functions· Lesson 20 of 32

Returning a value

Write a function that computes a number and returns it, then store the result in a variable.

About 7 min

Functions can hand a value back

So far our functions have *done* things (drawn shapes). A function can also compute a value and hand it back with the return keyword. The returned value takes the place of the call, so you can store it in a variable.

function double(n) {
  return n * 2;
}

let result = double(21); // result is now 42
double() returns a number you can use.

When the code hits return, the function stops and gives back that value. Here double(21) becomes 42, which we save in result.

Compute an area, then print it.

Return vs. print

println *shows* a value; return *hands it back* so your program can keep using it. They're not the same — a returned value can be added, compared, or passed along.

Your turn

Define a function area(w, h) that returns w * h. Then call it with area(20, 5) and store the result in a top-level variable named boxArea so it ends up equal to 100.

Hints