return ends a function straight away and gives back a value. Put one inside an if, and the function stops there when the condition is true, skipping the rest. This is often called an early return.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
function name(value) {
if (condition) {
return earlyValue;
}
return normalValue;
}
condition: the case where you already know the answer.return earlyValue: leaves the function with that value. Nothing after it in the function runs.return normalValue: the answer for every other case.
See return (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
A ticket price: children under 12 pay 5, everyone else pays 10. The file is ticket.js.
Step 1: Write the Code
function ticketPrice(age) {
if (age < 12) {
return 5;
}
return 10;
}
console.log(ticketPrice(8));
console.log(ticketPrice(30));
For a child, the first return ends the function, so the second one never runs.
Step 2: Run It
node ticket.js
5
10
Age 8 took the early return, and age 30 reached the last line.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Putting code after a return in the same block | It never runs | Put it before the return |
Writing the value without return inside the if | The function carries on and gives back the later value | Write return in front of the value |
FAQ
Can return have no value?
Yes. return; leaves the function, and the call gives back undefined.
Conclusion
An early return leaves a function as soon as the answer is known, which keeps the rest of the function for the normal case.
Additional Resources
- return (opens in a new tab) (MDN)
- Functions (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments