Navigating JavaScript Collections: A Comprehensive Guide to for Loops and the Differences between for and forEach
Types of For loops in Javascript
For iterating through data collections like arrays and objects, JavaScript offers a number of methods. This article will look at the three most common JavaScript loop types and point out their key differences.
The conventional for
loop is the first kind of for loop. Initialization, condition, and increment are the three elements that make up this loop. Initialization sets where the loop starts, the condition is checked before every iteration, and increment moves the loop to the next item.
for (let i = 0; i < 10; i++) {
console.log(i);
}
The code mentioned above will record 0 through 9 to the console. Prior to each iteration, the condition "i less than 10" is checked, and "i" is then increased by 1 by initializing the variable to 0.
For-in
loops make up the second category of for-loops. Iterating through an object's properties is accomplished using this loop. One by one, each property name is assigned to the loop variable.
const person = {
name: "John",
age: 30,
job: "developer"
};
for (let prop in person) {
console.log(prop + ": " + person[prop]);
}
In the code above, "name: John," "age: 30," and "job: developer" will be logged to the console. The loop variable prop takes on the value of each property name in the person object, and the person[prop] notation is used to access the value of each property.
The for-of loop is the third kind of for-loop. Iterating through an array's or other iterable object's elements is done using this loop. Each element's value is individually assigned to the loop variable.
const numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(num);
}
In the code above, the numbers 1 through 5 will be recorded to the console. Each component of the numbers array is represented by a single value in the loop variable num.
In conclusion, each of these for-loops in JavaScript has a specific function. The for-in loop is used for iterating over object properties; the for-of loop is used for iterating over the elements of an array; and the traditional for loop is used for counting and indexing. It is crucial to use the appropriate loop for the task at hand.
for vs forEach
To iterate over arrays or other iterable objects in JavaScript, use the for
and forEach
looping constructs. Although they both have a similar function, they are not identical and have some significant differences.
A starting point, an ending point, and an increment can all be specified using the for loop, a common looping construction. It is often used to loop through arrays with a known number of elements or to do a certain number of loops. Initialization, condition, and increment or decrement are the three elements that make up the for loop.
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
A callback function is passed as an argument when the forEach
method, an array method, is invoked on an array. A single call to this callback function is then made for each element of the array. The current iteration number and other control flow statements are not accessible via the forEach
method, in contrast to the for
loop.
arr.forEach(function(element) {
console.log(element);
});
One significant distinction between the two is that forEach
is restricted to arrays and cannot iterate over other kinds of objects. Another distinction is that a for
loop can be terminated using the break
statement, whereas a forEach
loop does not offer a way to exit the loop early.
In conclusion, iterating over arrays in JavaScript can be done using either for
or forEach
, but there are some significant functional and usage differences between the two. The for
loop is more flexible and gives you more control over the iteration process. The forEach
method, on the other hand, is easier to use and goes through an array more quickly.
Gotchas
The source array on which theforEach
method is used cannot have its elements modified.
The key utility of for of
loop over forEach
is while performing asynchronous operations. In real time, if you were to make a series of API calls in a loop, the forEach
initiates the calls and proceeds with execution of the next lines of code after the loop, even when the await
keyword is used. Whereas for of
loop waits for the completion of each and every await statement to be completed before proceeding with the next iteration and then the next lines of code.
// below is an array of userId's in a system
let user_ids = [1,3,5,9,72];
let users = [];
//getUserDetails(id) is tye async method that fetches user data
user_ids.forEach(async (user_id) => {
const user = await getUserDetails(user_id);
users.push(user);
});
const userNames = users.map((user) => {
return user.name;
});
userNames.forEach((name) => {
console.log(name);
});
// Output:
// Andy
// Aman
Because the code is being executed asynchronously, as can be seen in the above code, not all of the names associated with the provided user_ids are printed. By the time userNames are printed, the userData for all Ids haven't yet been returned.
The code must wait for the completion of each API call before printing all the userNames. A for of
loop can be used to accomplish this.
// below is an array of userId's in a system
let user_ids = [1,3,5,9,72];
let users = [];
//getUserDetails(id) is tye async method that fetches user data
for(const user_id of user_ids) {
const user = await getUserDetails(user_id);
users.push(user);
}
const userNames = users.map((user) => {
return user.name;
});
userNames.forEach((name) => {
console.log(name);
});
// Output:
// Andy
// Aman
// Tom
// Jerrry
// Bruto
Subscribe to my newsletter
Read articles from Sandeep Korrapati directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by