By TechQuest eAcademy · 10/24/2024
In this video, we dive deep into the world of loops in JavaScript, exploring three essential types: for, for...of, and while. Understanding when to use each type is crucial for writing efficient and effective code.
A loop is a programming construct that allows you to execute the same block of code multiple times. It is useful for:
The for loop is ideal when you know exactly how many times you want to execute a block of code. It provides complete control over the iteration process. The basic syntax includes initialization, condition, and increment. For example, counting from one to five:
for (let i = 1; i <= 5; i++) {
console.log(`Number ${i}`);
}
This will print numbers one through five. See the example.
You can also use a for loop to iterate through an array. For instance, if you have an array of fruits:
const fruits = ['apple', 'banana', 'cherry', 'date'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit at index ${i} is ${fruits[i]}`);
}
This will print each fruit in the array. Check it out.
The for...of loop is a cleaner way to iterate over iterable objects like arrays and strings. It allows you to access values directly without needing the index. For example:
for (const fruit of fruits) {
console.log(`Fruit: ${fruit}`);
}
This will print each fruit directly. Learn more about for...of.
You can also use the for...of loop to iterate through a string:
const name = 'John';
for (const letter of name) {
console.log(letter);
}
This will print each letter in the name. See the string example.
The while loop continues to execute as long as the specified condition remains true. Use this loop when the number of iterations is not known beforehand. For example, counting down from five:
let i = 5;
while (i > 0) {
console.log(i);
i--;
}
This will print numbers from five down to one. Explore while loop.
We covered three types of loops: for, for...of, and while. Each loop serves different purposes:
Thanks for watching! If you have any questions, feel free to drop them in the comments below. Subscribe for more tutorials.
3/27/2020
10/24/2024
9/30/2024
9/24/2024
9/22/2024
11/4/2020