Loops in JavaScript
Loops in JavaScript are like the GPS for your code, guiding it through repetitive tasks. They allow you to execute a block of code multiple times, saving you from writing the same thing over and over. Whether youāre iterating over arrays or looping until a condition is met, loops are your trusty companions in making your code more efficient and dynamic. Letās embark on a journey through the world of JavaScript loops.
List of Loops
1. For Loop
The classic workhorse, the for
loop, is excellent for iterating over a range of values.
for (let i = 0; i < 5; i++) {
console.log(i);
}
2. While Loop
The while
loop repeats a block of code as long as a specified condition is true.
let count = 0;
while (count < 3) {
console.log('Counting: ' + count);
count++;
}
3. Do-While Loop
Similar to while
, but the block of code is executed at least once, even if the condition is false.
let doCount = 0;
do {
console.log('Do count: ' + doCount);
doCount++;
} while (doCount < 3);
4. Forā¦in Loop
Perfect for iterating over the properties of an object.
const person = { name: 'John', age: 30 };
for (let key in person) {
console.log(key + ': ' + person[key]);
}
5. Forā¦of Loop
Introduced in ES6, this loop is great for iterating over iterable objects like arrays.
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
Conclusion
Loops in JavaScript are the navigators steering your code through repetitive journeys. They provide efficiency and flexibility, allowing you to perform tasks without redundancy. As you embrace loops in your coding adventures, your code becomes more dynamic and responsive.
Happy coding!
With loops at your command, your code journeys become smoother and more enjoyable.