ES6: JavaScript for…of statement

Introduction

This tutorial will learn about for-of introduced in ES6 version of JavaScript.

The for…of statement is used for iterating over arrays, maps or sets.

Looping over an array

Example in code:

const fruits = [‘Oran…


This content originally appeared on DEV Community and was authored by Naftali Murgor

Introduction

This tutorial will learn about for-of introduced in ES6 version of JavaScript.

The for...of statement is used for iterating over arrays, maps or sets.

Looping over an array

Example in code:

const fruits = ['Orange', 'Apple', 'banana', 'Lemon']

// looping through
for (fruit of fruits) {
  // do something with fruit
}

Looping over a string

for...of can also be used to loop over contents of a string.

const words = 'Happy new year!'
for (char of words) {
  console.log(char) // H a p p y n e w y e a r !
}

Looping over a Set

A set is a collection of unique values.

const letters = new Set(['a', 'b', 'c'])

for (letter of letters) {
  console.log(letters) // a, b, c
}

Looping over a map

A map is key-value pair, where key can be of any type. In JavaScript it's common to use object literals as maps

const details = new Map( [
  ['name', 'Michael Myers'],
  ['age', 45] // made up
])

// or a cleaner way:
const details = new Map()
details.set('name', 'Michael Myers')

for (detail of details ) {
  console.log(detail)
}

Summary

for...of introduces a cleaner way of looping over arrays, sets, strings and maps.

Read more about 👉 Map objects


This content originally appeared on DEV Community and was authored by Naftali Murgor


Print Share Comment Cite Upload Translate Updates
APA

Naftali Murgor | Sciencx (2022-01-18T19:24:39+00:00) ES6: JavaScript for…of statement. Retrieved from https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/

MLA
" » ES6: JavaScript for…of statement." Naftali Murgor | Sciencx - Tuesday January 18, 2022, https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/
HARVARD
Naftali Murgor | Sciencx Tuesday January 18, 2022 » ES6: JavaScript for…of statement., viewed ,<https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/>
VANCOUVER
Naftali Murgor | Sciencx - » ES6: JavaScript for…of statement. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/
CHICAGO
" » ES6: JavaScript for…of statement." Naftali Murgor | Sciencx - Accessed . https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/
IEEE
" » ES6: JavaScript for…of statement." Naftali Murgor | Sciencx [Online]. Available: https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/. [Accessed: ]
rf:citation
» ES6: JavaScript for…of statement | Naftali Murgor | Sciencx | https://www.scien.cx/2022/01/18/es6-javascript-for-of-statement/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.