Every function in JavaScript implicitly returns **undefined** if no `return` statement is reached. A `return` statement immediately exits the function. Multiple `return` statements in different branches are valid and common for guard clauses.
1Understanding return Statement
Every function in JavaScript implicitly returns undefined if no return statement is reached. A return statement immediately exits the function. Multiple return statements in different branches are valid and common for guard clauses.
Don't put a newline between return and the return value — ASI will insert a semicolon and your function will return undefined.
// Guard clause pattern
function divide(a, b) {
if (b === 0) return null; // guard
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // null2Practical Example
Here is a real-world application of return Statement showing how it is used in production JavaScript code.
// ASI pitfall with return
function broken() {
return // ASI inserts semicolon here!
{ value: 42 }; // never reached
}
function fixed() {
return {
value: 42 // opening brace on same line
};
}
console.log(broken()); // undefined
console.log(fixed()); // { value: 42 }3Best Practices
Follow these guidelines when working with return Statement:
1. Use early returns (guard clauses) to reduce nesting
2. Always explicitly return from functions that are expected to produce values
3. Avoid return on its own line with value on the next line — ASI bug
Tip: Don't put a newline between return and the return value — ASI will insert a semicolon and your function will return undefined.
// Guard clause pattern
function divide(a, b) {
if (b === 0) return null; // guard
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // null