Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false. A loop will continue running until the defined condition returns false.
Practice File : loops.js
The for
loop is the most commonly used loop. It has three parts: initialization, condition, and increment/decrement.
for (let i = 0; i < 5; i++) {
console.log(i);
}
The while
loop runs as long as the specified condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
The do...while
loop is similar to the while
loop, but it will always execute the block of code once before checking the condition.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
The for...in
loop is used to iterate over the properties of an object.
const obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key + ': ' + obj[key]);
}
The for...of
loop is used to iterate over iterable objects like arrays, strings, etc.
const arr = [1, 2, 3, 4, 5];
for (let value of arr) {
console.log(value);
}
Example: