What Return Statements Do
You'll learn how return statements send values back to the code that called your function and immediately stop the function's execution.
The Core Idea
A return statement does two critical things:
- Passes a value back to wherever the function was called
- Immediately exits the function, stopping any further code from running
Think of a function like a vending machine: you press a button (call the function), and it gives you a snack (returns a value). Once it delivers your snack, the transaction ends — it doesn't keep dispensing items.
How It Works
function add(a, b) {
return a + b; // Send the sum back
console.log("This never runs!"); // Code after return is unreachable
}
const result = add(5, 3);
console.log(result); // 8
When JavaScript hits return a + b, it:
- Calculates
5 + 3 - Sends
8back to the calling code - Exits the function instantly
The console.log after the return never executes.
Without Return
If you omit return, the function returns undefined by default:
function greet(name) {
console.log("Hello " + name);
// No return statement
}
const value = greet("Sam"); // Logs "Hello Sam"
console.log(value); // undefined
Return Without a Value
Using return alone exits early but still returns undefined:
function checkAge(age) {
if (age < 0) {
return; // Exit early with undefined
}
return "Valid age";
}
Key Takeaway: The return statement sends a value back to the caller and immediately exits the function — no code after return in that execution path will run.