The return statement
Learn to return a value from a function and early return.
The return statement
To hand a function's result back to the caller, you use the return keyword. return produces a value and ends the function. For example, function add(a, b) { return a + b; } returns the sum when called.
You can store the result in a variable: const sum = add(3, 5);. Now sum holds 8. Without return, the function only produces side effects, not a value.
What if there is no return?
If a function has no return or an empty one, JavaScript automatically returns undefined. That signals the function did not produce a value.
For example, function sayHi() { console.log("Hi"); } prints to the screen but returns undefined. Storing its result in a variable is rarely useful; the function is used for its side effect.
Exercise Compute price with tax
Define a function called priceWithTax. It should take a price parameter and return price * 1.2. Then print the result with console.log(priceWithTax(100)).
Show example solution
function priceWithTax(price) {
return price * 1.2;
}
console.log(priceWithTax(100));
Test yourself
-
What does this function return when called?
function square(n) { return n * n; } const result = square(4);- 16
- 8
- undefined
- 4
Show answer
16 — Correct. square(4) = 4*4 = 16.
-
Add the return keyword
function double(n) { ____ n * 2; } console.log(double(5));Show answer
function double(n) { return n * 2; } console.log(double(5)); -
Match each scenario to its result
- return 5;
- Returns the value 5
- return;
- Empty return -> undefined
- return a + b;
- Returns the sum a+b
- no return
- Automatic undefined