forEach() for — in & for — of loops in Javascript [easy-explained]

Humza Sajid
1 min readAug 5, 2021

Lots of time you heard of forEach for-in and for-of loop but you still struggle with how they work and why we need them?

Then today you are going to learn and master them (keep reading).

The basic idea of these loops is to iterate the array, many of you are already familiar with for loop

Syntax Example : for(var i=0; i<5; i++)

Now forEach() do the same work but with a minimal syntax

1 — forEach()

Let’s create an array to practice

let arr=[“Samsung”, “Huawei”, “Oppo”, “Xiaomi”,” Apple”];

now using forEach to iterate this array is easier than for loop.

arr.forEach( (function(abc) => console.log(abc));

2 — for- of

Now instead of declaring and initialization, we can use forOf (it’s majorly used for array, not objects).

for(const n of arr){

console.log(n);

}

3 — for -in

It works well for objects so let’s create an object to understand this

const tech={

YT: “YouTube”,

FB:” Facebook”,

MS:” Microsoft”

}

Now let’s use forin

for( const n in tech){

console.log(`Keys are ${n} and values are ${tech[n]};

}

--

--

Humza Sajid

Writing easy-to-understand Web-Application Development (JS/TypeScript, React, Node) explanations for myself and others.