The While Loop
The while loop has slightly simpler syntax than the for-loop that we covered in the previous module. The while loop tests a condition before each iteration. If the condition is true, the code inside the loop runs; if it’s false, the loop stops.
Basic Syntax
The syntax of a while loop is as follows:
while (condition) {
// Code to execute repeatedly as long as the condition is true
}
- condition: This is any expression that evaluates to a boolean (true or false). The loop checks this condition before each iteration.
- Code Block: If the condition returns true, JavaScript executes the statements inside the loop body. Once the condition becomes false, the loop stops, and the program moves on to the next statement after the loop.
☝️ The simple syntax of the while-loop means that if you want to use it for, e.g., incrementing a counter, you will have to define the counter before the loop starts, and you will have to manually increment the counter inside the loop.
Examples
Printing Numbers 1 to 5
One common use of a while loop is printing a sequence of numbers. For example, to print numbers from 1 through 5, you can create a counter variable and increment it on each loop iteration:
let i = 1; // Initialize the counter to 1
while (i <= 5) { // Continue looping as long as i is less than or equal to 5
console.log(i); // Print the current value of i
i++; // Increment i by 1
}
Explanation:
- We start by setting i to 1.
- The while loop checks if i is less than or equal to 5.
- Inside the loop, the current value of i is printed.
- The counter i is then increased by 1.
- The process repeats until i becomes 6; at that point, the condition i <= 5 evaluates to false, and the loop ends.
Calculating a Sum
Loops are also useful for performing calculations repeatedly. For example, to calculate the sum of the numbers 1 through 5, you keep a running total:
let total = 0; // Start with a total of 0
let i = 1; // Start counter at 1
while (i <= 5) {
total += i; // Add the current value of i to total
i++; // Increment i by 1
}
console.log(total); // After the loop, total is 15
Exercises
Print Numbers Using a While Loop
- Create a variable i and initialize it to 1.
- Use a while loop to print the numbers 1, 2, 3, 4, and 5 to the console.
- Make sure to update i inside the loop.
Calculate the Sum of Numbers 1 to 5 Using a While Loop
- Create a variable total initialized to 0 and a counter variable i set to 1.
- Use a while loop to add the numbers 1 to 5 to total.
- Print the final value of total using console.log.


Ready to become an ethical hacker?
Start today.
As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.