When dealing with an array, there is a number of ways one can iterate
through the elements starting from the first at index 0 all the way
to the last element in the array. In my learning process I have come
across 6 looping methods namely
for (let i = 0; i < arr.length; ++i)
which allow loop break and continue to skip a current iteration.for (let i in arr)
which allow object iteration as well as break and continue.do {code block to be executed}while (
condition
)
which allow break and continue even on an empty array.while(
condition
)
which works based on a condition and allow break and continue.arr.forEach((v, i) => { })
which does not have a loop break.for (const i of arr)
which as well allow for break and continue.From the 6 loops, the
forEach
is the recommended method when dealing with arrays, sets and objects. Why? For one the forEach is a more functional and declarative syntax compared to the rest. This allows us to iterate through the entire arrays without skipping or breaking. In addition one is able to execute each element based on the element value or it index. how?[1,2,3,4,"df"].forEach((value, index) => console.log(index,value));
output
0 1
1 2
2 3
3 4
4 'df'
Most JavaScript Style Guide enforces this as the
forEach
enforces the immutable rule as it is much reasonable to deal with pure functions that return a value with less side effects. ["a", "", "b"]
, the for (let i = 0; i < arr.length; ++i)
and the for (const i of arr)
will return undefined on the empty value in the arrays while the for (let i in arr)
skips the empty array.for (let i in arr)
tends to print out a value rather than ignoring it. Declare an arr = ['a', 'b', 'c']
, modify it arr.test = "boy"
, print it out [ 'a', 'b', 'c', test: 'boy' ]
. Looping, for (let i in arr) {console.log(arr[i]); }
, this will in fact return an output [ 'a', 'b', 'c', 'boy' ]
thus affirming our point that the use of for (let i in arr)
in arrays is generally a bad practice. There are more issues that i have not mentioned that strongly support the use of
arr.forEach((v, i) => { })
over the other looping methods. This are just some starting pointers for any developer who is still at the beginning of the learning process. Regardless, this is not to say that the arr.forEach((v, i) => { })
is the final and only way, the main point to understand before choosing a looping function is the type of data that you will be working with, though it's advisable to always prefer the use JavaScript higher-order functions over for-in
or for-of.