Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 29, 2023 02:51 pm GMT

JavaScript for of loop tutorial

In JavaScript, the for of loop is another way of iterating over an iterable object like an array, string, or set. It was introduced in ES6 and offers an alternative to the traditional for loop and for...in loop.

Syntax for a for of loop

for (let value of iterable) {  // code block}

Here, value is a variable that takes the value of the element in each iteration of the loop, and iterable is an object that has iterable properties, such as an array or a string.

for of loop Iterate over array

Iterating over an Array Let's start with an example of how to use the for...of loop to iterate over an array:

const numbers = ['one', 'two', 'three'];for (let number of numbers) {  console.log(number);}

In this example, we have an array of numbers, and we use the for of loop to iterate over each element of the array and log it to the console.

Output

onetwothree

for of loop Iterate over string

Iterating over a String You can also use the for of loop to iterate over a string

const hello = 'Hello World';for (let chr of hello) {  console.log(chr);}

We use the for of loop to iterate over each character in the string and log it to the console.

Output

HelloWorld

for of loop Iterate over Map

Iterating over a Map The for of loop can also be used to iterate over a Map object

const numbers = new Map([  ['One', 1],  ['Two', 2],  ['Three', 3]]);for (let [word, number] of numbers) {  console.log(`word: ${word} number: ${number}`);}

Output

word: One number: 1word: Two number: 2word: Three number: 3

Learn JavaScript tutorial


Original Link: https://dev.to/max24816/javascript-for-of-loop-tutorial-8bk

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