Sling Academy
Home/JavaScript/How to use the for…of loop in JavaScript (best practices)

How to use the for…of loop in JavaScript (best practices)

Last updated: February 19, 2023

This article covers everything you need to know about the for…of loop in JavaScript.

Overview

The for…of loop is a useful feature of JavaScript that simplifies the process of iterating over arrays, strings, and other iterable objects, without the need for manual index management.

The syntax:

for (let element of iterable) {
  // do something here
}

In this syntax, element represents the current element being iterated over, and iterable represents the collection being iterated. The loop will iterate over each element in the collection and execute the code block for each element.

Using for…of loop with arrays

One of the most common use cases for the for…of loop is with arrays.

In the example below, the for…of loop is used to iterate over an array called words and log each word to the console:

const words = ['spray', 'limit', 'elite', 'exuberant', 'slingacademy.com'];

for (let word of words) {
  console.log(word);
}

Output:

spray
limit
elite
exuberant
slingacademy.com

Using for…of with the “break” keyword

You can use the break keyword with for…of to exit the loop when and where you want.

Example:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const expectNum = 6;

for (let x of arr) {
  if (x === expectNum) {
    console.log(`${x} is the number we are looking for. Stopping loop`);
    break;
  } else {
    console.log(`${x} is NOT the number we are looking for`);
  }
}

Output:

1 is NOT the number we are looking for
2 is NOT the number we are looking for
3 is NOT the number we are looking for
4 is NOT the number we are looking for
5 is NOT the number we are looking for
6 is the number we are looking for. Stopping loop

Using for…of loop with strings

In Javascript, strings are iterable, so the for…of loop works well with them.

Example:

const s = 'Sling Academy';
for (let char of s) {
  console.log(char);
}

Output:

S
l
i
n
g
 
A
c
a
d
e
m
y

Using the for…of loop with objects

It is possible to use the for…of loop with objects, but there are some limitations. Objects are not iterable by default, but you can make them iterable by defining a Symbol.iterator method on the object.

Example:

const person = {
  name: 'Maidenless',
  email: '[email protected]',
  age: 39,
  location: 'The Lands Between',
};

// make the object iterable
person[Symbol.iterator] = function* () {
  const keys = Object.keys(this);
  for (let key of keys) {
    yield [key, this[key]];
  }
};

// use for..of loop to iterate over the object
for (let [key, value] of person) {
  console.log(`${key}: ${value}`);
}

Output:

name: Maidenless
email: [email protected]
age: 39
location: The Lands Between

This is actually a lot more laborious and time-consuming than necessary. Instead, you should use the for…in loop with objects.

Using for…of for Iterating over DOM elements

In the example below, the for…of loop is used to iterate over all DOM elements with a class of button. The loop then adds a click event listener to each button that logs a message to the console when clicked:

const buttons = document.querySelectorAll('.button');

for (let button of buttons) {
  button.addEventListener('click', () => {
    console.log('Button clicked!');
  });
}

Note that this code only works on web browsers (not Node.js).

Best Practices

Here are some best practices to improve the performance and readability of your code when using the for…of loop:

  • Use the loop with arrays and iterable objects, but be cautious when using it with non-iterable objects.
  • It’s better to declare the loop variable with let to avoid accidentally creating a global variable.
  • Don’t modify the collection while iterating: Modifying the collection being iterated over can lead to unexpected behavior. To avoid this, create a copy of the collection if you need to modify it during the iteration.
  • Use descriptive variable names: Choose descriptive variable names for your loop variables to make your code more readable and understandable.
  • Use the break statement to exit the loop early if it has done its job. This will help reduce computing resource consumption.

That’s it. Happy coding!

Next Article: JavaScript Self-Invoking Functions: Tutorial & Examples

Previous Article: How to use for…in loop in JavaScript: Best practices

Series: Mastering Control Flow in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration