All the Different Ways to Go Through a List in JavaScript
There are many ways to go through an array list in JavaScript. I want to share some that I found while learning:
The
forloop is the first one that I learn. This loop allows the flexibility to set the starting point, the endpoint, and how much to move between each item. Read more about theforloop here.const array = [1, 2, 3]for (let i = 0; i < array.length; i++) {console.log(array[i])}// expected output:// 1// 2// 3The second way is the
forEach()method on the array. Unlike theforloop, we do not need to set the starting position, the endpoint, or how much to move between each element. Because of this, we lose the flexibility of theforloop. TheforEach()method will go through every item, moving up one index at a time. This is useful if this is the behavior that you want since you're writing less! Read more about theforEach()method here.const array = [1, 2, 3]array.forEach((element) => console.log(element))// expected output:// 1// 2// 3The third way is to use a library like Underscore and Lodash. These popular libraries provide a useful method called
each(), which acts similarly toforEach(). Read more abouteach()here and here.import _ from 'underscore'const array = [1, 2, 3]_.each(array, (element) => console.log(element))// expected output:// 1// 2// 3Lastly, I learned that ES6 provides a new way to go through an array, called the
for...ofloop. I haven't had a chance to use this much, but you can read more about it here.const array1 = ['a', 'b', 'c']for (const element of array1) {console.log(element)}// expected output:// 1// 2// 3
There are many ways to go through an array. Use the one you like best for your situation!