Loops are essential constructs in programming that allow you to execute a block of code repeatedly. In JavaScript, there are several types of loops, each serving different purposes. Let’s dive into each one with code examples.
1. for
Loop :-
The for
loop is used when you know how many times you want to iterate.
for (let i = 0; i < 5; i++) {
console.log("Iteration", i);
}
2. while
Loop :-
The while
loop is used when you want to iterate based on a condition.
let i = 0;
while (i < 5) {
console.log("Iteration", i);
i++;
}
3. do...while
Loop:-
Similar to the while
loop, but it ensures that the code block is executed at least once before the condition is checked.
let i = 0;
do {
console.log("Iteration", i);
i++;
} while (i < 5);
4. for...in
Loop :-
Iterates over the enumerable properties of an object.
const person = {
name: "John",
age: 30,
gender: "male"
};
for (let key in person) {
console.log(key, ":", person[key]);
}
5. for...of
Loop :-
Introduced in ES6, it iterates over iterable objects like arrays, strings, etc.
const fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Conclusion
Understanding loops in JavaScript is fundamental for any developer. Each loop type serves different use cases, offering flexibility in handling iterations within your programs.