Topic 55 of 87
Return Statements
Overview
When JavaScript reaches a return statement, the function immediately stops executing and outputs the specified value back to the caller.
If a function finishes executing its entire body without hitting a return statement, it implicitly returns undefined.
Syntax
Standard Return and Early Return
javascript
function isAdult(age) {
if (age < 18) {
// Execution stops completely right here!
return false;
}
// This code NEVER runs if age < 18
console.log("User is an adult!");
return true;
}Common Pitfalls
- Automatic Semicolon Insertion (ASI) bugs. If you write
returnand put the value on the next line without parentheses, JS automatically inserts a semicolon after the wordreturn, causing your function to returnundefinedinstead of your value!
Interview Questions
Q:
What is an 'Early Return' (or Guard Clause)?
A:
It is a pattern where you write if (errorState) return; at the very top of a function. By returning early on invalid data, you avoid wrapping the rest of the function in massive, deeply nested if/else blocks, keeping the code flat and readable.
Real-World Example
Using Guard Clauses in a payment processor to ensure data is pristine before charging a card.
example
javascript
function chargeCard(user, amount) {
if (!user) return;
if (amount <= 0) return;
if (!user.hasCard) return;
// Safely process charge here
}Check Your Knowledge
Test your understanding of Return Statements with these quick questions.