DEV Community

Cover image for For In and For Of in Javascript
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

For In and For Of in Javascript

Hey fellow developers

Let's learn the differences between the loops For... In and For... Of in Javascript in less than a minute!

If you prefer to watch the video version, it's right here :

1. The For... Of loop.

The For... Of loop is used to iterate through iterable elements, for example arrays, strings, nodelists, etc. It has the following syntax:

const array = [1, 2, 3];

for(const item of array){
    console.log(item);
}
// in the console :
// 1
// 2
// 3
Enter fullscreen mode Exit fullscreen mode

It will basicaly create a new constant for each element.

If you use a string, it'll be exactly the same:

const str = "123";

for(const item of str){
    console.log(item);
}
// in the console :
// "1"
// "2"
// "3"
Enter fullscreen mode Exit fullscreen mode

2. The For... In loop.

The For... In loop is used to iterate through an object.

const tiger = {
    paws: 4,
    weight: 300,
    height 100
}

for(const prop in tiger){
    console.log(prop);
    console.log(tiger[prop]);
}
// in the console :
// "paws" 4
// "weight" 300
// "height" 100
Enter fullscreen mode Exit fullscreen mode

Here you can access the property name with "prop" and/or the property value with tiger[prop].

You now know the differences between these two loops!

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (2)

Collapse
 
deathshadow60 profile image
deathshadow60

1) Don't const inside for, you're telling the scripting engine not to release the variables when done.

2) You play with Object.entries and destructuring yet?

const tiger = {
paws: 4,
weight: 300,
height 100
}

for (let [name, value] in Object.entries(tiger)) {
console.log(name, value);
}

Fun stuff.

Collapse
 
ziratsu profile image
Ustariz Enzo

Sigh, how I love that Stack overflow tone :).

1) There is no problem using const inside for..in or for..of loops.
On the contrary it adds a level of security if you don't want to reassign the value of the variables inside of the loop.
Do you have some sources of "you're telling the scripting engine not to release the variables when done.", I'll be happy to read it.

2) Indeed I know destructuring and that funky syntax, but you need to use a for...of loop with the Array returned by Object.entries, else you won't have what you are trying to accomplish.