Loading...
Loading...
Get results back from functions. The output of computation.
return sends a value back to the caller and stops execution.
function multiply(a, b) { return a * b; // sends result back // code after return NEVER runs } let result = multiply(4, 5); console.log(result); // 20
Key rules:
return immediately exits the functionundefinedreturn; with no value also gives undefinedfunction noReturn() { console.log("hello"); // no return statement } let x = noReturn(); console.log(x);
Exit early to avoid deep nesting. A clean code pattern.
Deeply nested
function process(user) {
if (user) {
if (user.active) {
if (user.verified) {
return doWork(user);
}
}
}
return null;
}Early return
function process(user) {
if (!user) return null;
if (!user.active) return null;
if (!user.verified) return null;
return doWork(user);
}// Guard clauses — check invalid cases first: function divide(a, b) { if (b === 0) return "Cannot divide by zero"; return a / b; } function getAge(birthYear) { if (!birthYear) return null; if (birthYear > 2026) return null; return 2026 - birthYear; }
Functions often return complex values.
function createUser(name, age) { return { name: name, age: age, isAdult: age >= 18, }; } const user = createUser("Alice", 25); console.log(user.name); // "Alice" console.log(user.isAdult); // true
// Return arrays: function getMinMax(arr) { return [Math.min(...arr), Math.max(...arr)]; } const [min, max] = getMinMax([3, 1, 7, 2]); // min = 1, max = 7
Return an array and destructure the result for clean multi-value returns.
JavaScript can only return one thing — but that thing can contain many values.
// Pattern 1: Return an object function getStats(numbers) { return { min: Math.min(...numbers), max: Math.max(...numbers), avg: numbers.reduce((a, b) => a + b) / numbers.length, }; } const { min, max, avg } = getStats([1, 2, 3, 4, 5]); // Pattern 2: Return an array function divide(a, b) { return [Math.floor(a / b), a % b]; } const [quotient, remainder] = divide(17, 5); // quotient = 3, remainder = 2
💡 Prefer objects when returning named values (self-documenting). Use arrays when values have a natural order (like coordinates).
Common questions about return values.