In this tutorial I will tell you the difference between
for of and
for in loops.
A collection is an object which contains a group of elements. For example: arrays, set, list, custom collections etc.
foreach is an method that is available only in Array objects. It allows you to iterate through elements of an array. When invoked it takes a callback function and invokes the callback once for every array element. The callback can access both index and value of the array elements.
foreach is available only for looping arrays.
for in is used to loop through properties of an object. It can be any object.
for in will only walkthrough a property if it has
[[Enumerbale]] set to
true. It not used to iterate elements of an collection rather used to iterate properties of objects.
for of is a new way for iterating collections. Its introduced in ES6. Earlier you had to use
while loop to iterate through elements of an collection. For
for of to work on an collection, the collection must have an