Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
Return as soon as you know the answer
Some PHP style guides push a single return at the bottom of a function. Early returns are equally valid in PHP and are the default habit in many JavaScript codebases — especially for parsing, validation, and lookups.
PHP habit: one exit vs early exit
<?php
function discountForRole(string $role): int {
$percent = 0;
if ($role === 'admin') {
$percent = 20;
} elseif ($role === 'member') {
$percent = 10;
} elseif ($role === 'guest') {
$percent = 0;
} else {
return 0;
}
return $percent;
}
<?php
function discountForRole(string $role): int {
if ($role === 'admin') {
return 20;
}
if ($role === 'member') {
return 10;
}
if ($role === 'guest') {
return 0;
}
return 0;
}
Both are legal PHP. The second version maps line-for-line to JavaScript without a trailing $percent variable.
JavaScript equivalent
function discountForRole(role) {
if (role === 'admin') return 20;
if (role === 'member') return 10;
if (role === 'guest') return 0;
return 0;
}
| Situation | Early return helps |
|---|---|
| Unknown role / bad input | Stop before more logic runs |
| Empty list | if (items.length === 0) return [] |
| Cache hit | if (cached) return cached |
Guard clauses vs early returns
Guard clauses are early returns for invalid cases. Early returns also cover happy shortcuts (found a match, nothing to do). The technique is the same: leave the function when the outcome is known.
Failure mode: returns inside loops
Returning from inside a for loop exits the whole function, not just the iteration. In PHP you might continue; in JavaScript use continue, break, or Array.prototype methods from lesson 2.11.
Try it
Use the amber Try it panel below. Click Run.
function parsePort(value) {
if (value === '' || value == null) return { ok: false, error: 'Port required' };
const n = Number(value);
if (Number.isNaN(n)) return { ok: false, error: 'Port must be a number' };
if (n < 1 || n > 65535) return { ok: false, error: 'Port out of range' };
return { ok: true, port: n };
}
for (const v of ['', 'abc', '0', '443', '70000']) {
console.log(v, '->', parsePort(v));
}
Each failure path returns immediately; the success path is one block at the end.
From PHP to JavaScript — Control Flow, Functions, and Scope