12JavaScript
While Loops - Repeating an action until a condition is true
Easy
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:
JAVASCRIPT
1while (condition) {
2 // Code to execute repeatedly as long as the condition is true
3}- 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.
1 / 4
Hakatemia Pro
Learn to hack — start here
Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.