Hone

Lessons · JavaScript · while loops

Repeat until something changes

while (condition) repeats as long as the condition holds; use it when you do not know how many times in advance.

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

Retry until success, read until the end, walk a chain until null: all 'until', not 'this many times'.

How to think about it

When should this stop, and what moves it there? Write the stop condition first, then make sure something inside the loop changes it every turn.

Worked example

let n = 27, steps = 0;
Until n reaches 1.
while (n !== 1) {
Stop condition.
  n = n % 2 === 0 ? n / 2 : 3 * n + 1;
Something changes each turn.
  steps++;
Count.
}

Your turn

Keep halving until below 1.

while (x  1) x = x / 2;

The trap

Forgetting to change the variable in the condition. The tab hangs.

Practise while loops on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.