Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 16, 2021 07:57 am GMT

for of loop in JavaScript

This post was originally published on webinuse.com

We have already written about loops in JavaScript in the article JavaScript Arrays Loops. Now we will introduce a new one for of loop.

for of loop is similar to forEach loop, but with for of loop we can use break and continue. This is something that makes it even more appealing.

The syntax for for of loop is pretty simple and straightforward.

The first parameter of for of loop is the loop variable and the second parameter is the array that we are iterating through. If we want to break out from the loop, we have to use keyword break.

const arr = [1, 2, 3];for (const el of arr) {   if (el === 3) break;   console.log(el)}//Result//1//2

Also, we can skip iteration by using keyword continue.

const arr = [1, 2, 3];for (const el of arr) {   if (el === 2) continue;   console.log(el)}//Result//1//3

Often, while working with loops we need to know the current index. We can accomplish that, with for of loop, by using entries().

const arr = ['js', 'py', 'php'];for (const el of arr.entries()) {   console.log(el)}//Result://[0, 'js']//[1, 'py']//[2, 'php']

In the example above console.log returned the index and value of the current index, in the form of an array. But we can simplify this even further by destructuring the array. This means that we can extract values from the array, along with the index, as separate variables.

const arr = ['js', 'py', 'php'];for (const [index, el] of arr.entries()) {   console.log(index)   console.log(el)}//Result://0//js//1//py//2//php

But we have to be careful if we are using destructuring. ALWAYS index comes the first and element comes the second. Also, we can use const in this case, because every new iteration for of loop creates a new scope.

If you have any questions or anything you can find me on myTwitter, or you can read some of my other articles likeWhat is object destructuring in JavaScript?.


Original Link: https://dev.to/amersikira/for-of-loop-in-javascript-2ce3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To