Hone

Lessons · JavaScript · leave as soon as you know

Leave as soon as you know

return ends the function immediately; handle the simple cases first and the main path stays unindented.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Deeply nested if/else is where bugs hide. Guard clauses at the top make the rest read top to bottom.

How to think about it

Which inputs have an obvious answer? Empty, null, zero, already done. Check those first, return, then write the real logic without an else.

Worked example

function firstWord(text) {
First word of a sentence, or empty text.
  if (!text) return "";
The simple case, answered and gone.
  return text.split(" ")[0];
The real case, not inside an else.
}

Your turn

Return 0 immediately for an empty array.

function average(xs) {
  if (xs.length === 0)  0;
  return xs.reduce((a, b) => a + b) / xs.length;
}

The trap

Code after a return in the same block never runs. If you see it, it is dead.

Practise leave as soon as you know on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.