Oakland, CA 94608, USA
+415-816-5171
jt@jtwebarchitect.com

forEach vs for…in in JavaScript

Jampa Thinlay Tsarong Web Architect

Created with Sketch.

forEach(), we have to specify a callback function. This callback function will
be executed on each element in the array.
It can only be used on Arrays, Maps, and Sets.

For example:

const myArray = ['book', 'bike', 'apple'];
    myArray.forEach(element => {
    console.log(element);
    });

Outcome:

// book
// bike
// apple

For…in is 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 properties we add to an
object will be the most part be enumerable, however the Object.keys() method.
These are non-enumerable. Examples below might help us better to understand
this concept.
For Example:

const objects = {
    a: 1, 
    b: 2, 
    c: 3,
    d: 4
 }
for (let element in objects){
    console.log(objects[element])
}

Outcome:

 // 1
 // 2
 // 3
 // 4

We can console log out both the key and value pair:

For example:

for (let element in object) {
    console.log(`${element} = ${object[element]}`);
}

outcome:

    // a = 1
    // b = 2
    // c = 3
    // d = 4

We can also use the for…in loop on Arrays:

For Example:

   const myArray ['book', 'bike', 'apple'];
    for (let i in myArray){
        console.log(myArray[i])
    }

Outcome:

 // book
 // bike
 // apple

We can even use for…in on string.

For example:

    const string = 'welcome';
       for (let character in string){
           console.log(string[character])
       } 

Outcome:

    // w 
    // e 
    // l 
    // c 
    // o 
    // m 
    // e

The for…in loop executes in an arbitrary order and should not be
relied upon if you need to loop in a specific order.