For...in & For...of
Open the project folder
In our starter files, open the index.html page from this lessons folder:
06.Loops-and-conditionals > 02.For-in-for-of
Starter file example
We will now cover two more types of loops, called for…in and for…of. They look similar as they both loop over something, but the key difference is what they can loop over.
Let’s open the starter files and see what we have:
// for...in - (object properties)
const product = {
sku: 'CSMBLUE',
name: 'Cool shirt',
size: 'medium',
color: 'blue',
};
// for...of - (iterable objects eg Array, NodeList...)
const permissions = ['user', 'editor', 'admin'];
First, we see the for…in section and an object containing a product. This is how a for…in loop works. We can use it to loop over the properties inside of an object, such as the name and size.
Below we have the for…of section, and this is used for looping over iterable objects. This just means an object we can loop over, and this includes things like arrays and node lists.
The for…in loop
First, we can try out for…in to loop over the properties of an object:
// for...in - (object properties)
const product = {
sku: 'CSMBLUE',
name: 'Cool shirt',
size: 'medium',
color: 'blue',
};
for (const property in product) {
console.log(`${property} : ${product[property]}`);
}
The property variable becomes the current object property on each loop. The following will be logged to the console:
sku : CSMBLUE
index.html:20 name : Cool shirt
index.html:20 size : medium
index.html:20 color : blue
The for…of loop
The for…of will loop over iterable objects, such as an array:
// for...of - (iterable objects eg Array, NodeList...)
const permissions = ['user', 'editor', 'admin'];
for (const value of permissions) {
console.log(value);
}
Using this example, the value variable holds the current array value on each loop. Things like NodeList can also be looped over too, and remember, when we use querySelectorAll to get multiple elements, this is what we get back.
To try this out we need some HTML elements:
<body>
<!-- ADD THE FOLLOWING UL -->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
We can then select all these links using querySelectorAll:
const links = document.querySelectorAll("li");
for (const link of links) {
// we can then use this link and add an event listener to each one:
link.addEventListener("click", function (e) {
alert(e.target.innerHTML);
});
}
Click on each element and you will see an alert with the innerHTML content. Bothe of these are variations of the for loop. And next, we are going to look at the while loop.