What are they? When and how can we use them?
This is the case with for, forEach, and for-in/of loops. These are two ways of iteration we learned in class at Operation Spark.
In this blog post I will be explaining each method of iteration and the differences between the three methods.
For Loop
The most primitive way of iterating over an array is with a for loop.
A for loop takes in three arguments: initial expression, a stop condition, and increment expression. We can see an example of this syntax in the example pictured below.
In this code snippet we are trying to iterate through the array declared on the first line. While we iterate we want to push the odd numbers into the oddNumbers array declared on the second line. On the fourth line of code, we are declaring the variable i to represent the index of an element within the array, nums. Then, we declare the stop condition for the function to be called until i is less than the length of the nums array. Ultimately, to increment the index we will increase the value of i after each iteration.
This is what the resulting console output after running the for loop. We see the value of the oddNumbers array printed after each iteration.
forEach
forEach is a built in array prototype method that functions similarly to a for loop. It executes a function once on each element in the array. The forEach method exists within an array’s prototype. Since all arrays inherit Array.prototype, the forEach method is available in all arrays in javascript
A simpler, cleaner for loop?
We can achieve the similar functionality as a for loop with small key differences. In this code snippet we assign the variable oddNum to a forEach loop similar to the for loop in the previous example.
The forEach method takes in the parameter num and checks to see if it is an odd number which then it will be pushed into the oddNumbers array. We can see the console logs the same values from when we used the for loop below.
Differences:
forEach functions are neater and easier to read.
forEach variables are scoped to its block, meaning outside variables can be used freely within a forEach function.
for loops are faster in execution time.
for loop allows to break out of the loop early, while forEach iterates through each element in the array.
Personally I try to use forEach whenever I can because it allows for me as a developer to read neater code making it
easier to write functions and solve different problems in *Javascript. *
Thank you for reading my blog post! I hope you learned something that can be applied in your everyday coding.
Thanks for reading,
Bilal Hankins






Top comments (0)