Looping Arrays (The for-of Loop)

Firyal
2 min readMar 15, 2022

--

There is a new way for looping array! This was introduced in ES6. What is it? It is the for-of loop. The Javascript for of statement loops through the values of an iterable object. It lets us loop over iterable data structures such as arrays, string, array-like objects (arguments), and others. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

The syntax:

variable — For every iteration, the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.

iterable — An object that has iterable properties.

syntax

For-of looping Arrays

We have some properties array. We want to log the all of menu in starterMenu and mainMenu. First, we can use spread operator to spread the array of starterMenu and mainMenu, after that we can use for-of looping to console it. We make a new variable item using const, and console the item.

for-of looping array

The result is will be like this:

Focaccia
Bruschetta
Garlic Bread
Caprese Salad
Pizza
Pasta
Risotto

The object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

We can see the example of using entries() below. We type menu.entries() inside the for-of looping. and

object.entried()

We will get the arrays result of the [key and value]:

[ 0, 'Focaccia' ]
[ 1, 'Bruschetta' ]
[ 2, 'Garlic Bread' ]
[ 3, 'Caprese Salad' ]
[ 4, 'Pizza' ]
[ 5, 'Pasta' ]
[ 6, 'Risotto' ]

Another example:

another example

--

--