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 …

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

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"



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

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/Learntocreate/videos

See you soon!

Enzo.


Print Share Comment Cite Upload Translate
APA
Ustariz Enzo | Sciencx (2024-03-29T15:50:23+00:00) » For In and For Of in Javascript. Retrieved from https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/.
MLA
" » For In and For Of in Javascript." Ustariz Enzo | Sciencx - Wednesday December 15, 2021, https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/
HARVARD
Ustariz Enzo | Sciencx Wednesday December 15, 2021 » For In and For Of in Javascript., viewed 2024-03-29T15:50:23+00:00,<https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/>
VANCOUVER
Ustariz Enzo | Sciencx - » For In and For Of in Javascript. [Internet]. [Accessed 2024-03-29T15:50:23+00:00]. Available from: https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/
CHICAGO
" » For In and For Of in Javascript." Ustariz Enzo | Sciencx - Accessed 2024-03-29T15:50:23+00:00. https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/
IEEE
" » For In and For Of in Javascript." Ustariz Enzo | Sciencx [Online]. Available: https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/. [Accessed: 2024-03-29T15:50:23+00:00]
rf:citation
» For In and For Of in Javascript | Ustariz Enzo | Sciencx | https://www.scien.cx/2021/12/15/for-in-and-for-of-in-javascript/ | 2024-03-29T15:50:23+00:00
https://github.com/addpipe/simple-recorderjs-demo