For loop vs. forEach vs. for…in vs. for…of
This article will show a quick introduction of a for loop, a forEach, a for of, and a for in. We are going to talk about what are their differences and similarities in this article.
For Loop
This method is the most traditional type of iteration in Javascript. It takes three expressions; a variable declaration and expression to be evaluated before each iteration, and an expression to be evaluated after each iteration. Let's dive into an example.
We are setting a variable i=0 before the loop starts. It will continue to loop as long as i <arr. length (which is 4), and each iteration of the loop will increment the i by one. Finally, within the brackets, the execution code will be run on each iteration of the loop.
ForEach
This method executes with a callback function( a function passed to another function as an argument ). It can only be used on Arrays, Maps, and Sets.
When using forEach, there is a call back function where it is executed on each array element. However, it won’t allow statements ‘break’ to exit for loop, ‘continue’ to skip an iteration, or ‘return’ to return a value(and exit the loop).
For…In
Mostly used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value- if that value is set to true, then the property is Enumerable.
The key property is being displayed. The array displays the relevant indexes, as internally, the array is stored in the form of a key-value pair (keys start from 0).
Arrays are objects too, which means we can also use the for…in loop. As well as string, each string has an index.
For …Of
Mostly used to iterate over iterable objects. Usually utilizing to iterate values in an array of most array-like objects such as maps. Unlike forEach(), you can use “break,” “continue,” and “return.”Two advantages of ‘for-of’ over ‘for-in’ are that. First, it visits indices of an array in numeric(ascending) order. Second, indices of arrays are not converted to strings, so executing arithmetic is much more concise.
for…of is also offers a lot of flexibility such as pictures down below
And that's it! That is the introduction of for loop, forEach, for…in, and for…of. I hope it helps you to clarify something!