Technical skill practice

JavaScript while(true): Stop on a Sentinel and Keep a Safety Bound

while (true) repeats until control leaves the loop. For an input-driven task, make the stopping condition and an independent safety bound visible. Do not demonstrate termination by hoping an unbounded busy loop eventually stops.

The task

Read a short command list until END, preserving only commands before the sentinel. Reject missing termination rather than running forever or pretending the whole input was valid.

Runnable Node 22 example

const assert = require('node:assert/strict');

function readCommands(input, limit = 5) {
  const accepted = [];
  let index = 0;
  while (true) {
    if (index >= limit || index >= input.length) throw new Error('missing END');
    const command = input[index++];
    if (command === 'END') break;
    accepted.push(command);
  }
  return accepted;
}
assert.deepEqual(readCommands(['scan', 'file', 'END', 'ignored']), ['scan', 'file']);
assert.throws(() => readCommands(['scan']), /missing END/);
assert.throws(() => readCommands(['scan', 'file', 'END'], 2), /missing END/);
console.log(readCommands(['scan', 'file', 'END']).join(','));

Expected output and explanation

The loop checks available input and the configured bound before reading a command. Encountering END exits without appending it; later input is not processed. The second failure shows that a sentinel beyond the allowed reads is not accepted.

The limit is a maximum number of reads including a possible terminator, not a count of accepted work commands. Stating that meaning avoids an off-by-one surprise when a caller chooses the bound.

Output from the example

scan,file

Pitfall to check

This synchronous example only reads a supplied array. A real asynchronous input source needs appropriate awaiting, cancellation and resource handling rather than a CPU-bound loop waiting for new data.

Questions, answered

Is while(true) always a bug?

No. It can express a clear sentinel-driven loop, but every path must have a deliberate termination or failure policy that suits the input source.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.