DEV Community

SCDan0624
SCDan0624

Posted on

Intro to Loops Part 2

In my last blog we went over the two more commonly used loops: for loop and while loop. Now let's take a look at two newer loops that are now being used: For in and For of loops.

For Of Loop
The for/of lets you loop over data structures that are iterable such as Arrays, Strings, and others.

The syntax of a for/of loop is:

for (variable of iterable) { statement } 
Enter fullscreen mode Exit fullscreen mode

Example
Let's say we have the following array

const myArr = ["dog","cat","snake","mouse"]; 
Enter fullscreen mode Exit fullscreen mode

If we wanted to go through and print every element of this array we can do that easily using a for/of loop:

const myArr = ["dog","cat","snake","mouse"]; for(const element of myArr){ console.log(element) } /* output dog cat snake mouse */ 
Enter fullscreen mode Exit fullscreen mode

this is a much easier and cleaner way to iterate through an array than using a regular for loop:

const myArr = ["dog","cat","snake","mouse"]; for(let i=0;i<myArr.length;i++){ console.log(myArr[i]) } 
Enter fullscreen mode Exit fullscreen mode

The for/of loop is create for iterating through arrays but what about the objects? That is where our next loop comes into play:

For In Loop

The for/in loop is used to loop through the properties of an object. The syntax of a for/in loop is:

for (variable in object){ statement } 
Enter fullscreen mode Exit fullscreen mode

Example
What if we wanted to iterate through the following object and print the values of each key?

const basketballTeam = { Guard:"Curry", Forward:"Leonard", Center:"Boban" } 
Enter fullscreen mode Exit fullscreen mode

You can easily do this with a for/in loop

const basketballTeam = { Guard:"Curry", Forward:"Leonard", Center:"Boban" } for(const property in basketballTeam) { console.log(basketballTeam[property]) } /*Output Curry Leonard Boban */ 
Enter fullscreen mode Exit fullscreen mode

If you only wanted to print the keys you could do that too:

const basketballTeam = { Guard:"Curry", Forward:"Leonard", Center:"Boban" } for(const property in basketballTeam) { console.log(property) } /*Output Guard Forward Center */ 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)