JavaScript: for...in Loop

Profile picture for user arilio666

In javascript, a 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 value from a property through an everyday notation object[variable].

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
  • Here we decided to create an object with properties of key-value pair.
  • We are using the for in to fetch the values of the properties.
  • So first of all, we are declaring a variable of our own called finalDetail it can be any name we want.
  • We are pointing that variable to the object details.
  • So now, obviously, when we try to print finalDetail, it'll fetch all the keys from the property because for in does that, and it is its sole purpose to do that.
  • 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.
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.