Ads and ad measurement. Disabled until you allow it.
ABOUT SITE
All open site tabs
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.
Quick topic start and explanations before exercises (exercises below):
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."
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).
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.
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;
}
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;
}
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;
}
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);
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;
}
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);
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);
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);
}
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);
No split tab
Cookie preferences
We use necessary cookies to run the site. With your permission, we can also save your site preferences and use analytics and advertising cookies to understand usage and support the project.
Open tools in tabs.Exercises, IDE tools, and trainers stay available as site tabs.
Switch without losing context.Move between explanations, code, and utilities while keeping your place.
Use the sidebar as your map.The left panels hold navigation, settings, files, libraries, and tool controls.
PythonJavaScriptSQLite
One IDE, three practical modes
Python in the browser.Run small scripts, try libraries, and practice API requests without installing anything.
JavaScript for quick experiments.Test browser-friendly code and compare ideas next to your learning materials.
SQLite for data practice.Open the database explorer to inspect tables, write queries, and learn SQL workflows locally.
TopicIDE
Work side by side with split tabs
Keep instructions visible.Open an exercise or reference page beside the IDE instead of jumping back and forth.
Compare tools while you learn.Place regex checks, explanations, and code experiments next to each other when the task needs it.
Close the split when you are done.The workspace returns to a single focused tab, and your open site tabs remain available.
Code Typing Trainer
Or plain text
This trainer is designed for a physical keyboard.Open this section on a laptop or desktop with a wide screen. Touch typing practice will not work correctly on a phone.
Speed: 0 chars/min
0 words/min
Best speed (60s): 0 chars/min
0 words/min
Errors: 0
Total time: 0.0 s
To practice touch typing, avoid looking at your physical keyboard.