DEV Community

Shameel Uddin
Shameel Uddin

Posted on

πŸ”„ Looping Through JavaScript Arrays with Different Approaches πŸ”„

Introduction

Arrays are a fundamental data structure in JavaScript, allowing you to store and manipulate collections of values. Looping through arrays is a common task in JavaScript, and there are several approaches to achieve this. In this blog post, we'll explore different methods to loop through JavaScript arrays, each with its unique strengths and use cases.

1. The Classic For Loop πŸƒβ€β™‚οΈ

The classic for loop is a workhorse when it comes to iterating through arrays. It provides fine-grained control over the loop, and you can easily access array elements by their index. Here's an example:

const fruits = ['🍎', '🍌', 'πŸ‡', '🍊'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
Enter fullscreen mode Exit fullscreen mode

This approach is efficient and versatile but can be a bit verbose compared to newer methods.

2. The forEach Method 🀝

Introduced in ECMAScript 5, the forEach method simplifies array iteration. It takes a callback function as an argument, which is executed for each element in the array. This approach is more concise and easier to read:

const animals = ['🦁', '🐘', 'πŸ¦„', '🐧'];

animals.forEach((animal) => {
  console.log(animal);
});
Enter fullscreen mode Exit fullscreen mode

The forEach method is great for readability, but it doesn't provide the same level of control as the for loop.

3. The for...of Loop πŸšΆβ€β™€οΈ

ES6 brought us the for...of loop, a clean and concise way to iterate over iterable objects like arrays. It abstracts the index management, making the code cleaner:

const colors = ['πŸ”΄', '🟒', 'πŸ”΅', '🟣'];

for (const color of colors) {
  console.log(color);
}
Enter fullscreen mode Exit fullscreen mode

This approach combines the advantages of the classic for loop and the forEach method, offering simplicity and control.

4. The Map Function πŸ—ΊοΈ

Mapping an array is another method that allows you to loop through an array while creating a new one with the results. It applies a function to each element and returns a new array:

const numbers = [1, 2, 3, 4, 5];

const squaredNumbers = numbers.map((number) => {
  return number * number;
});

console.log(squaredNumbers);
Enter fullscreen mode Exit fullscreen mode

The map function is powerful when you need to transform data in the array.

5. The Filter Function πŸ”

The filter function is similar to map but returns a new array containing elements that meet a specified condition. It's handy for selecting specific items from an array:

const scores = [80, 90, 65, 70, 95];

const passingScores = scores.filter((score) => score >= 70);

console.log(passingScores);
Enter fullscreen mode Exit fullscreen mode

Filtering is an excellent way to extract data based on certain criteria.

Conclusion

Looping through JavaScript arrays is a common task in web development. Each approach has its own strengths and use cases. Whether you prefer the classic for loop, the simplicity of forEach, the elegance of for...of, or the transformation and filtering capabilities of map and filter, the choice is yours.

Mix and match these methods depending on the problem you're solving, and you'll be well-equipped to work with arrays in JavaScript.

Happy coding! πŸŽ‰πŸ’»βœ¨

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (10)

Collapse
 
leodarpan profile image
DARPAN ANEJA

Very helpful

Collapse
 
shameel profile image
Shameel Uddin

Thank you

Collapse
 
ravavyr profile image
Ravavyr

For the record.
The basic javascript for loop can do everything the other loops do, is easier to read and understand and also performs faster than all of them [you can look up benchmarks]

So the real question is....why do we have so many ways of accomplishing the exact same thing? [but that's a whole can of worms in the javascript ecosystem]

Collapse
 
tailcall profile image
Maria Zaitseva

In a language that aims for backward compatibility you can't simply remove old features (the dreaded with operator still works in modern environments), so similar features pile up over time.

Collapse
 
shameel profile image
Shameel Uddin

Maybe JS decided to look cool and get out of C++ era of traditional for-loop? (JK)

Collapse
 
yutamago profile image
Yutamago

They're not unique to Javascript.
Those are patterns you find across most modern programming languages. Javascript supports them to make your life easier and code more readable.
If you really need the extra performance, chances are that Javascript is not the right language for your use case anyway.
And even in Javascript, there's way more promising patterns to maximize performance.

Collapse
 
ravavyr profile image
Ravavyr

Lol "if i need the performance js is not the right language" ?
What other language do you suggest i use for intensive UI interactions in the browser? I'm pretty sure JS is the only one available for that. And mostly it makes pages janky when devs add too many loops that aren't optimized. It's not something i run into every day, but a few times a year it makes sense to convert some map or other into a basic for loop just to speed it up.

Collapse
 
joewilliamdd31 profile image
Mr. Lucky

I love to look cool so I use for of and foreach loop

Collapse
 
cloudwalker_143 profile image
Surya-Sujit

Im getting typeof() of the map as an object.

Collapse
 
danchooalex profile image
danchooalex

Nice article!