Getting a Value Back

The greet function from the last lesson printed something. Most functions instead calculate a value and give it back to the code that called them. They do this with return:

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

const result = double(21);
console.log(result);
console.log(double(double(10)));

Output:

42
40

A call to a function that returns is a value. You can use it anywhere a value fits: store it in a variable, print it, or pass it to another call. In double(double(10)), the inner call runs first and gives 20. Then 20 is the argument of the outer call, which gives 40.

return also ends the function right away. Together with if, this lets you leave a function early:

function category(age) {
  if (age < 13) return "child";
  if (age < 20) return "teenager";
  return "adult";
}

console.log(category(8));
console.log(category(16));
console.log(category(35));

Output:

child
teenager
adult

You do not need else here. Each return leaves the function, so only one of them runs for each call.

What does a function give back if it has no return? It gives back undefined:

function cheer() {
  console.log("Hooray!");
}

const x = cheer();
console.log(x);

Output:

Hooray!
undefined

This leads to a common beginner bug: printing a result instead of returning it. A function that uses console.log for its answer shows the answer on the screen, but the code that called it gets undefined. If you then do math with that value, you get NaN.

So remember this rule: printing is for people, and returning is for code. Let your functions calculate and return. Keep the console.log calls in the main part of the program. Then the caller can decide what to do with the result: print it, compare it, or pass it to another function.

In the exercise, complete two functions that return a square and an average.