Functions
return
Ends the function and hands a value back to whoever called it.
Why it exists
A function is a little machine: something goes in, something comes out. return is the way out. Without it the result would stay locked inside the function: you couldn't store it in a variable, pass it on or compare it. That's why challenges check what a function returned, not what it printed.
Where it's used
- Compute and hand back a result:
return price * count. - Early exit: "if there's no data,
returnright away" instead of wrapping all the code in an if. - Stop searching as soon as the answer is found:
return trueright inside a loop. - Pass a result into another function:
formatPrice(calcTotal(cart)).
Syntax
return expression;Examples
function square(x) {
return x * x;
}
square(4); // → 16
function noReturn(x) {
console.log(x * x);
}
noReturn(4); // → undefined — prints 16 but returns undefinedfunction total(prices) {
let sum = 0;
for (const p of prices) sum += p;
return sum;
}
const bill = total([120, 80]);
bill; // → 200
bill * 2; // → 400function greet(name) {
if (!name) return "Hello, guest!";
return "Hello, " + name + "!";
}
greet(""); // → "Hello, guest!"
greet("Ann"); // → "Hello, Ann!"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
When execution reaches return, the function ends immediately: nothing after it runs, even if the return is inside a loop. The value to the right of return becomes the value of the call — in your code, sum(2, 3) literally "turns into" 5.
If a function ends without return (or with a bare return;), it returns undefined. That way every call always has some value.
console.log is something else entirely: it shows a value to a human in the console, but gives nothing back to the program.
Traps
When to pick something else
If a function exists only for an action (show a notification, write to a log), it doesn't have to return anything. And to stop one step of a loop rather than the whole function, there are continue and break.
Practice
Lessons where this appears
- How Byte stopped repeating himselfTale · Chapter 2 · Functions
- Why isn't console.log the same as return?Why? · Chapter 2 · Functions
- The case of the empty receiptInvestigation · Chapter 2 · Functions
- The Great UndefinedBoss · Chapter 2 · Functions
- Byte becomes a bouncerTale · Chapter 3 · Conditions
- The case of the white screenInvestigation · Chapter 15 · Errors