Lesson 6 of 15

While Loops

While Loops

A while loop keeps running as long as its condition is true:

let n = 1;
while (n <= 4) {
    console.log(n);
    n++;
}
// prints 1, 2, 3, 4

Use while when you do not know in advance how many iterations you need.

Halving a Number

function halvingSteps(n) {
    let steps = 0;
    while (n > 1) {
        n = Math.floor(n / 2);
        steps++;
    }
    return steps;
}
console.log(halvingSteps(8));   // 3  (8→4→2→1)
console.log(halvingSteps(100)); // 6

Your Task

Write function countDigits(n) that returns the number of digits in n. Use a while loop that divides by 10 until nothing remains.

Special case: countDigits(0) should return 1.

JavaScript loading...
Loading...
Click "Run" to execute your code.