Skip to main content

JavaScript: Difference between for...in and for...of Loop

For(..in) Loop

  • the for-in loop can perform an advanced loop and fetches all the keys in a property and all the indexes in an array. Typically we can fetch the keys from a property through an everyday notation object[variable]. 
  • To put it simply it loops through the enumerable(able to be counted by one-to-one ) properties of an object. It simply iterates over keys.

For(..in) Syntax

for(variable in object)
{
    //condition
}

Example

let details = 
{
    firstName : "Stephen",
    lastName : "Strange",
    occupation : "Sorcerer Supreme",
    gender : "male"
}

for(let finalDetail in details)
{
    console.log(finalDetail+ " : " +details[finalDetail])
}

Output

firstName : Stephen
lastName : Strange
occupation : Sorcerer Supreme
gender : Male
  • As for in loop fetched the index of key-value pair here, we are working on object-based properties.
  • When we try to use the notation of object[variable]/details[finalDetail] and print it, it'll fetch all the fundamental values, as you can witness from the code.

For(..in) Loop With Array

let infinityStones = ['Soul', 'Time', 'Reality', 'Power', 'Mind', 'Space']

for(let stones in infinityStones)
{
    console.log(stones)
}

Output

0
1
2
3
4
5
  • As you can see, when we try to use for in in an array, it fetches and returns the indexes of each element present in the array.

For(..of) Loop

  • For of is another alternative to for in, which is more accessible than for in. Here it fetches and returns the value of each element in an array instead of fetching the index. Generally iterable over arrays, strings, maps and node lists, etc.
  • Rather than operating on the index, it operates on the value of each property. It simply iterates over values.

For(..of) Syntax

for(variable of object)
{
    //condition
}

Example

let infinityStones = ['Soul', 'Time', 'Reality', 'Power', 'Mind', 'Space']

for(let stones of infinityStones)
{
    console.log(stones+ " Stone ")
}

Output

Soul Stone
Time Stone
Reality Stone
Power Stone 
Mind Stone
Space Stone
  • As you can see here, it caught the element's value directly after iterating through the infinity stones and focuses only on the content of the array.
  • This one cannot be used in object property as for in loop does.
Tags
Submitted by arilio666 on December 24, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.