Skip to main content
0 reactions

How to Stop a Function Early with return in JavaScript

A card titled Return Early from a Function, labelled JavaScript Basics, showing an early return of 5 for an age under 12, with ticketPrice(8) giving 5 and ticketPrice(30) giving 10.
Return Early from a Function: Leave a function as soon as you have the answer.

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

SyntaxJavaScript
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

The Example

A ticket price: children under 12 pay 5, everyone else pays 10. The file is ticket.js.

Step 1: Write the Code

ticket.jsJavaScript
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

TerminalBash
node ticket.js
OutputPlain text
5
10

Age 8 took the early return, and age 30 reached the last line.

Common Mistakes

MistakeWhat happensDo this instead
Putting code after a return in the same blockIt never runsPut it before the return
Writing the value without return inside the ifThe function carries on and gives back the later valueWrite 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments