JS class for each

JS class for each

When it comes to iterating over arrays or objects in Javascript, there are several ways to achieve this. One of the commonly used methods is by utilizing the forEach method which is available on arrays. However, if you are dealing with a large dataset or you want to have more control over the iteration process, using the for..in loop or the for..of loop can be more appropriate.

The forEach method

The forEach() method executes a provided function once for each element in an array.


const arr = [1, 2, 3];

arr.forEach(element => {
    console.log(element);
});

In the code snippet above, we are iterating over an array of numbers and logging each element to the console using an arrow function. The forEach() method is invoked on the arr array, and it takes a callback function as an argument. This callback function is executed once for each element in the array.

The for..in loop

The for..in loop is used to iterate over the properties of an object. It works by iterating over all enumerable properties of an object, including those inherited from its prototype chain.


const obj = {a: 1, b: 2, c: 3};

for(let prop in obj) {
    console.log(prop + ': ' + obj[prop]);
}

In the code snippet above, we are iterating over the properties of an object and logging each property name and its value to the console using string concatenation. The loop is terminated once all properties have been processed.

The for..of loop

The for..of loop is used to iterate over iterable objects such as arrays, strings, and maps. It works by iterating over the values of an iterable object.


const arr = [1, 2, 3];

for(let value of arr) {
    console.log(value);
}

In the code snippet above, we are iterating over an array of numbers and logging each value to the console. The loop is terminated once all values have been processed.

As you can see, there are different ways to achieve iteration in Javascript depending on your use case. Each method has its advantages and disadvantages, so it's important to choose the appropriate one based on your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe