JavaScript · Syntax · Beginner

while loop

14 tasks

Exercises on the while loop in JavaScript: repetition of actions, counters, sums of numbers, input to the desired condition, break, string sorting, and basic character processing.

How the while loop works

#
The while loop keeps running its body as long as a condition is true. Unlike for, which visits each element in a sequence, while keeps going until something makes the condition false. ```javascript let i = 1; while (i <= 10) { console.log(i); i++; } ``` i++ is the standard increment — it adds 1 to i. You will also see i += 1, which means the same thing. JavaScript does not have Python's i += 1 preference; both forms are equally common. JavaScript checks the condition before every iteration, including the first. If the condition is false at the start, the body never runs. The most common mistake: forgetting to update the variable the condition depends on. If i never changes, the loop runs forever. Always make sure something inside the loop moves you toward the exit condition. break exits the loop immediately. It is useful when the exit point is in the middle of the body: ```javascript while (true) { const password = prompt("Enter password: "); if (password === "secret") { break; } console.log("Wrong, try again"); } ``` while (true) is an intentional infinite loop that relies entirely on break to stop. This pattern is standard for "keep asking until valid input."

Counters, accumulators, and the sentinel pattern

#
Three patterns appear across almost all while-loop exercises. Counter: start at some value, increment or decrement each iteration, stop at a boundary. ```javascript let i = 1; while (i <= 10) { console.log(i); i++; } ``` Accumulator: start a total at zero, add each value to it inside the loop. ```javascript let i = 1; let total = 0; while (i <= 100) { total += i; i++; } console.log(total); ``` Sentinel: keep reading input until the user provides a stop signal (like 0). In these exercises, the stop condition is usually passed in directly as part of the problem. ```javascript let total = 0; let num = parseInt(prompt("Enter a number (0 to stop): ")); while (num !== 0) { total += num; num = parseInt(prompt("Enter a number (0 to stop): ")); } console.log(total); ``` These three patterns combine. A multiplication table uses a counter. A digit counter uses a counter and Math.floor(n / 10) to peel digits off one at a time (equivalent to Python's integer division).

Iterating through strings with while

#
The while loop works well for iterating through strings by index when you need more control than for...of gives you — moving backwards, jumping steps, or building a result character by character. Printing a string in reverse: ```javascript const word = "JavaScript"; let i = word.length - 1; while (i >= 0) { process.stdout.write(word[i]); i--; } ``` i starts at the last index and counts down to 0. process.stdout.write avoids adding a newline after each character (equivalent to Python's end=""). Building a filtered string — keep only characters that are not in a set: ```javascript const punctuation = "!@#$%^&./,?|"; const text = "Hello, world!"; let result = ""; let i = 0; while (i < text.length) { if (!punctuation.includes(text[i])) { result += text[i]; } i++; } console.log(result); ``` punctuation.includes(text[i]) checks whether the character appears in the punctuation string. The ! negates it, so only non-punctuation characters are added to result.
01

Numbers from 1 to 10.

#

Print the numbers from 1 to 10 using a while loop.

let i = 1;
Solution
let i = 1;
while (i <= 10) {
    console.log(i);
    i += 1;
}

// or you can do this: place the stopping condition inside the loop
let i = 1;

while (true) {
    if (i > 10) {
        break;
    }
    console.log(i);
    i += 1;
}
02

Countdown from 10.

#

Print the numbers from 10 to 1 in reverse order.

let i = 10;
Solution
let i = 10;
while (i >= 1) {
    console.log(i);
    i -= 1;
}

// or you can do this: use a condition greater than zero
let i = 10;

while (i > 0) {
    console.log(i);
    i -= 1;
}
03

Numbers up to the entered value.

#

The user enters a number. Print all numbers from 1 to this number.

let n = 5;
let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= n) {
    console.log(i);
    i += 1;
}
04

Only even numbers up to a number.

#

The user enters a number. Print only even numbers from 1 to this number.

let n = 5;
let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= n) {
    if (i % 2 === 0) {
        console.log(i);
    }
    i += 1;
}

// second option: immediately iterate only through even numbers
let n = 10;
let i = 2;

while (i <= n) {
    console.log(i);
    i += 2;
}
05

Sum from 1 to 100.

#

Find the sum of all numbers from 1 to 100 using a while loop.

let i = 1;
let total = 0;
Solution
let i = 1;
let total = 0;
while (i <= 100) {
    total += i;
    i += 1;
}
console.log("Sum:", total);

// or you can do this using the formula for the sum from 1 to n
let total = (100 * 101) / 2;
console.log("Sum:", total);
06

Sum up to the entered number.

#

The user enters a number. Find the sum of all numbers from 1 to this number.

let n = 5;
let i = 1;
let total = 0;
Solution
let n = 5;
let i = 1;
let total = 0;
while (i <= n) {
    total += i;
    i += 1;
}
console.log("Sum:", total);
07

Multiplication table.

#

The user enters a number. Print the multiplication table for this number from 1 to 10.

let n = 5;
let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= 10) {
    console.log(`${n} x ${i} = ${n * i}`);
    i += 1;
}

// or you can do this: calculate the product first
let n = 5;
let i = 1;

while (i <= 10) {
    let result = n * i;
    console.log(`${n} x ${i} = ${result}`);
    i += 1;
}
08

Password until correct input.

#

The user enters a password. Keep asking for the password until it equals "javascript".

let password = "";
Solution
let password = "";

while (password !== "javascript") {
    console.log("Wrong password");
    password = "javascript"; // simulation of new input
}

console.log("Password accepted");
09

Sum of numbers until zero.

#

The user enters numbers. The program should calculate the sum of entered numbers until the user enters 0.

let total = 0;
let num = 5;
Solution
let total = 0;
let num = 5;

while (num !== 0) {
    total += num;
    // In a real program, you can get the next value here.
    // For the example, let's end the loop.
    num = 0;
}

console.log("Sum:", total);
10

Counting digits in a number.

#

The user enters a number. Count how many digits are in this number. You may solve it without a loop in any way.

let num = 5;
Solution
let num = -12345;
let count = String(Math.abs(num)).length;

console.log("Number of digits:", count);
11

Word backwards.

#

Print the word backwards in the terminal.

let word = "иладеп";
Solution
let word = "pedali";
console.log(word.split('').reverse().join(''));

// or:
word = "pedali";
let drow = "";
let index = word.length - 1;
while (index > -1) {
    drow += word[index];
    index -= 1;
}
console.log(drow);
12

Text between identical symbols.

#

I probably got carried away here and this task is probably not simple. But that's okay, let's slowly think step by step about what needs to be done. Task: There is a string with any information, for example: 'Company LLC "Horns and Hooves" won some procurement tender.' You need to extract the part between identical symbols. For example, in this case, to get the company name, you need to extract the text between quotation marks. Do not use the split string method. Use only the index method!! You can experiment and solve the task without a loop or with a loop, however you like. P.S. You will need slices, and make text input and symbol input for the repeated symbol between which to extract using input. P.P.S See the string methods table. The index method returns the index of the FIRST occurrence of a symbol in a string (it does not return the second one unless you somehow make it become the first one in some intermediate string).

let text = "JavaScript";
let symbol = "a";
Solution
let text = 'Company LLC "Horns and Hooves" won the tender';
let symbol = '"';

let startIndex = text.indexOf(symbol);

if (startIndex === -1) {
    console.log("Symbol not found");
} else {
    startIndex += 1;
    let newText = "";

    while (startIndex < text.length) {
        let char = text[startIndex];

        if (char === symbol) {
            break;
        }

        newText += char;
        startIndex += 1;
    }

    console.log(newText);
}
13

Letter stairs.

#

This one is simple: There is a string "stairs", print it in the terminal like this: s -t --a ---i ----r -----s

let text = "ступеньки";
Solution
let word = "stairs";
let i = 0;

while (i < word.length) {
    console.log("-".repeat(i) + word[i]);
    i += 1;
}
14

Removing punctuation from text.

#

There is a list of punctuation marks and special symbols: punctuation = "!@#$%^&./,?|" And there is a text string where they may appear. Form a new string without punctuation marks, leaving only the text, keep spaces. That's all that needs to be done.

let punctuation = "!@#$%^&./,?|";
let text = "I guess we'll finish on this exercise. Enough! We want to rest! #@&#@&!!!";
Solution
let punctuation = "!@#$%^&./,?|";
let text = "I guess we'll finish on this exercise. Enough! We want to rest! #@&#@&!!!";

let newText = "";
let idx = 0;

while (idx < text.length) {
    let char = text[idx];

    if (!punctuation.includes(char)) {
        newText += char;
    }

    idx += 1;
}

console.log(newText);