Summary
To create a while loop in JavaScript, use the while
keyword:
let i = 0;
while (i < 10) {
// Insert code here
i++;
}
Details
A while loop lets you easily repeat a block of code multiple times.
To write a while loop, first declare your counter variable. Unlike a for loop, you declare your counter outside of the loop.
let i = 0;
Next, write the skeleton of the while loop.
let i = 0;
while () {
}
Next, write the condition to test against in parentheses.
let i = 0;
while (i < 10) {
}
Next, add an increment or decrement statement to the end of your loop. Without this, you might accidentally create an infinite loop!
let i = 0;
while (i < 10) {
i++;
}
Lastly, add the code you want to repeat.
let i = 0;
while (i < 10) {
console.log("Hello world");
i++;
}
Demo
Exercises
Try the following statements in the console:
let i = 0;
while (i < 5) {
console.log("Hello world");
i++;
}
You should see ‘hello world’ print out 5 times, or the phrase ‘hello world’ with a number 5 next to it.