- Courses
- 💻Programming Languages
- 🌐JavaScript
- Foundations
- Control Flow
- Loops
On this page
Loops in JavaScript
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
For loop
for loop: This is a control flow statement that allows code to be executed repeatedly. A for loop is made up of four parts: initialization, condition, final-expression, and statement.
for (initialization; condition; final - expression) {
// statement
}
Here’s an example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
For-In loop (through objects)
for-in loop: The for-in loop is used to loop through the properties of an object.
for (variable in object) {
// statement
}
Here’s an example:
let person = { firstName: "John", lastName: "Doe", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
For-Of loops (through iterables)
- for-of loop: The
for-ofloop is used to loop over iterable objects, like arrays and strings.
for (variable of iterable) {
// statement
}
Here’s an example:
let arr = [3, 5, 7];
for (let value of arr) {
console.log(value);
}
While loop
while loop: A while loop executes its statements as long as a specified condition evaluates to true.
while (condition) {
// statement
}
Here’s an example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Do-While loop
do-while loop: The do-while loop is similar to the while loop, except that the condition is tested at the end of the loop, so the loop will always be executed at least once.
do {
// statement
} while (condition);
Here’s an example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
If-Else and Switch statements
Next
Truthy & Falsy Values
-
For loop
- For-In loop (through objects)
- For-Of loops (through iterables)
-
While loop
-
Do-While loop
