Home › Learn › JavaScript › Loops

while loops

Lesson 12 of 40. Repeat until a condition stops holding.

while (condition) { ... } keeps running as long as the condition is true. Use it when the number of rounds is not known in advance. Something in the body must move toward the condition becoming false, or the loop never ends; the lesson runner stops runaway code after a few seconds and tells you.

n = Math.floor(n / 10) chops the last digit off a whole number, which is the usual way to walk through digits. do { ... } while (condition) is the variant that always runs the body at least once.

let n = 1;
let steps = 0;
while (n < 100) {
  n *= 2;
  steps++;
}
console.log(n, steps);   // 128 7

Your task

Write digits(n) returning how many digits a non-negative whole number has, by repeatedly dividing by 10 (digits(0) is 1), and pad(text, width) returning the text with spaces added on the right until it is width characters long (unchanged when it is already that long or longer), the way receipt columns are lined up.

Part of the final project. pad lines up the receipt columns by padding each label to a fixed width. It is saved in this browser and loaded into Project: checkout when you get there.

Hint 1

Handle 0 first, then: let count = 0; while (n > 0) { n = Math.floor(n / 10); count++; }

Hint 2

while (text.length < width) text += " "; return text;

Show the solution
function digits(n) {
  if (n === 0) return 1;
  let count = 0;
  while (n > 0) {
    n = Math.floor(n / 10);
    count++;
  }
  return count;
}

function pad(text, width) {
  while (text.length < width) text += " ";
  return text;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.