Loops with Arrays
Iterating Through Data
Arrays and Loops are best friends. If you have an array of 50 users and need to print their names, you use a loop to iterate through the array.
The Classic for Loop
Since arrays are zero-indexed, we start our loop counter at 0 and run it as long as the counter is strictly less than the array's length.
let users = ["Himanshu", "Alice", "Bob"];
for (let i = 0; i < users.length; i++) {
console.log("Welcome " + users[i]);
}
The for...of Loop
ES6 introduced the for...of loop, which is a much cleaner way to loop through arrays when you don't care about the index number.
let frameworks = ["React", "Next.js", "Tailwind"];
for (let framework of frameworks) {
console.log("I love " + framework);
}
This does the exact same thing as the classic for loop but requires much less typing and is less prone to "off-by-one" errors!
The forEach() Method
Arrays also have a built-in method called forEach(). It takes a function and runs it for every single item in the array.
let scores = [10, 20, 30];
scores.forEach(function(score) {
console.log(score * 2);
});
💡 Himanshu's Tip:
I highly recommend getting comfortable with the for...of loop and array methods like forEach. They make your code much more readable than traditional for loops!
Interview Questions
- What happens if you use
<=instead of<in a classicforloop condition while iterating an array? - What is the difference between a
for...inloop and afor...ofloop? - Can you use a
breakstatement inside aforEach()loop?