close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Understanding Javascript for of with index

Understanding Javascript for of with index
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Learn how to use JavaScript's for...of loop with indexes, explore methods to access indexes, and understand best practices for efficient coding. Discover advanced usage with Maps and Sets.

If you're curious about using JavaScript's for...of loop with indexes, here's a quick guide to understand it better:

  • for...of loop makes iterating through collections like arrays and strings straightforward, without the need to manage indexes manually.
  • However, to access indexes while using for...of, you can employ the .entries() method, which returns both the index and value of each item.
  • For index-only needs, the .keys() method provides a list of indexes, useful when you don't need to work directly with the collection's values.

Quick Comparison

Method Gets Index Gets Value Best Use Case
entries() Yes Yes When both index and value are needed
keys() Yes No When only the index matters
  • Best Practices: To optimize your JavaScript code, consider whether you need indexes, choose the right method (entries() for both item and index, keys() for index only), and avoid altering the original array during iteration.
  • Advanced Usage: Indexes are particularly useful when working with Maps and Sets, allowing for ordered operations and easy data management.

This guide aims to keep things simple and clear, helping you decide when and how to use indexes effectively in your JavaScript loops.

Basic JavaScript

  • Arrays - How to make them, get stuff out of them, and use array actions like .push(), .pop(), and more.
  • Objects - How to create them and get to their parts.
  • Functions - How to set them up, use them, what they take in, and what they give back.
  • Loops - The basics of going over items one by one using for and while.
  • Syntax - Understanding the basics like naming things, making choices with if/else, and checking things against each other.

Knowing the basics of JavaScript will help you get the hang of for...of loops much faster.

ES6

for..of came out with ES6, so you'll want to be comfy with some of the new stuff from that update:

  • let and const - Ways to name things that stay inside blocks.
  • Template literals - Making strings with backticks (`
  • Arrow functions - A short way to write functions with =>.
  • Destructuring - Taking parts out of arrays or objects and putting them into their own spots.

These bits are often used with for..of, so it's good to know them.

Iterables

for..of loops go over things that can be gone through one item at a time. Here's what you need to know:

  • What it means for something to be iterable.
  • How to use Symbol.iterator to set up how to go through something.
  • The step-by-step of using next() to move through items.

Getting how iterables work in JavaScript is key to really using for..of well.

With a solid start on these topics, you'll be all set to learn about for..of loops, how to work with indexes, and how to use this pattern in your coding.

Understanding the for...of Loop

The for...of loop is a simple way to go through items one by one in things like lists (arrays), text (strings), maps, and more in JavaScript.

Here's how you write it:

for (variable of iterable) {
  // code block to execute for each item
}

Let's break this down:

  • variable - Each time the loop runs, this variable will have the current item from the list or collection.
  • iterable - This is the collection of items you want to go through. It needs to have a way to go through each item, one by one.
  • code block - The set of instructions that will run for every item in the collection. You can use the variable to work with the current item.

Here's an example of going through a list of fruits:

const fruits = ["apple", "banana", "orange"];

for (let fruit of fruits) {
  console.log(fruit);
}

// Prints: 
// apple
// banana  
// orange

The good things about using a for...of loop are:

  • It's easy and straightforward for going through items.
  • It works with different kinds of collections, not just lists. You don't have to worry about keeping track of positions (indexes).
  • It keeps things tidy by limiting the variable to each loop.
  • You can stop (break) or skip (continue) items if you need to.

But, if you need to know the position of each item, for...of doesn't tell you that straight away. However, you can still find it out by using the Array.prototype.entries() method:

const fruits = ["apple", "banana", "orange"];

for (let [index, fruit] of fruits.entries()) {
  console.log(index, fruit);
}

// Prints:
// 0 'apple'
// 1 'banana'
// 2 'orange'

This method gives you back a pair of the position and the item each time the loop runs. You can then split them into separate variables.

In short, for...of is a neat, simple way to go through items in a collection. And when you need the positions, .entries() is there to help.

The Challenge with Indexes in for...of

When you use the for...of loop in JavaScript, it's great for going through items in a list or characters in a string one by one. But it doesn't automatically tell you where you are in the list or string (like, which number item you're on). Knowing the position, or index, can be really helpful for things like:

  • Updating items in a list based on their position.
  • Keeping track of items with numbers to link them to other info.
  • Making sure things stay in the right order when you move them around.
  • Checking your work by seeing where you are in the list.
  • Working with list features that need you to know the position, like how long the list is.

To also get the index while you're going through each item, you can use a trick with Array.prototype.entries(). This gives you both the item and its position:

for (let [index, value] of array.entries()) {
  // now you can use both index and value
}

But, this approach isn't perfect:

  • It might feel a bit more awkward than just counting as you go in a simple loop.
  • It could slow things down a bit because it's making extra steps happen in the background.

So, while for...of is mainly about focusing on the items without worrying about their positions, using entries() lets you keep track of both when you need to. It's a bit of a workaround, but it gets the job done when positions are important.

Methods to Access Index in for...of

Using Array.prototype.entries()

The entries() method is like getting a list where each item is a pair: one part is the item's position in the list (index), and the other part is the item itself. This is super handy in a for...of loop when you want to know both the item and where it sits in the list:

const fruits = ["apple", "banana", "orange"];

for (let [index, fruit] of fruits.entries()) {
  console.log(index, fruit); 
}

// 0 "apple"
// 1 "banana"  
// 2 "orange"

Here, we split the pair into two separate pieces using array destructuring. This means we can easily use the position and the item separately in each loop.

The big plus is you get both the item's position and its value directly. The downside is it might run a bit slower than a normal for loop because it's doing extra work behind the scenes.

Using Array.prototype.keys()

If you're only interested in the position of the items in your list and not the items themselves, the keys() method gives you just that. It hands back a list of positions:

const fruits = ["apple", "banana", "orange"];

for (let index of fruits.keys()) {
  console.log(index); 
}

// 0
// 1
// 2

This is good for when you just need to know where you are in the list. The upside is its simplicity - you get a straightforward list of positions. The downside is you miss out on direct access to the items, meaning you'd have to use array[index] to grab them.

Comparing Methods

Let's look at how Array.prototype.entries() and Array.prototype.keys() stack up when you're using them in a for...of loop in JavaScript to get the index:

Method Gets Index Gets Value Performance Use Case
entries() Yes Yes Slower When you need both index and value
keys() Yes No Faster When you only need the index

entries()

This method gives you both the index and the item itself every time you loop. It's great when you need to use both details. However, it's a bit slower because it has to create extra stuff in the background to work.

Benefits:

  • Easy access to both index and item
  • Straightforward to use

Downsides:

  • A bit slower
  • Uses more memory because of the extra stuff it creates

keys()

This method only gives you the index of each item. You don't get the item itself, which means you have to grab it in another step. But, it's quicker and uses less memory than entries().

Benefits:

  • Quicker
  • Uses less memory

Downsides:

  • You have to get the item separately
  • Not as straightforward

In short, if you need to know both the index and what the item is while you're looping, entries() is your go-to. But if you're okay with just knowing the index and getting the item another way, keys() is quicker and simpler.

Pick the one that fits what you're trying to do - whether you need everything upfront or you're okay with an extra step to get the item.

sbb-itb-bfaad5b

Advanced Usage

Accessing the index in for...of loops can be really handy, especially when you're dealing with Maps and Sets in JavaScript.

Using Indexes with Maps

Maps let you keep track of data as key-value pairs. Knowing the index while looping through a Map can be useful for things like:

  • Sorting the Map based on the order you added stuff.
  • Linking index positions to keys so you can find them easily later.
  • Deleting entries if you know their position.

Here's an example:

const fruitCalories = new Map([
  ["apple", 95],
  ["banana", 105],
  ["orange", 45]
]);

for (let [index, [fruit, calories]] of fruitCalories.entries()) {
  console.log(`#${index} ${fruit}: ${calories} calories`); 
}

// #0 apple: 95 calories  
// #1 banana: 105 calories
// #2 orange: 45 calories

This way, you loop through the Map and keep an eye on the position of each fruit entry.

Using Indexes with Sets

Sets are all about storing unique stuff. Getting the indexes can come in handy when:

  • You're trying to keep the order of things you added to the Set.
  • You want to match index positions with values for easy lookup later.
  • You're looking to remove things based on where they are in the Set.

Here's how you might do it:

const favorites = new Set(["pineapple", "grapes", "bananas"]);

for (let [index, fruit] of [...favorites].entries()) {    
  console.log(`#${index} favorite: ${fruit}`);
}

// #0 favorite: pineapple  
// #1 favorite: grapes
// #2 favorite: bananas

By turning the Set into an array first, you can use .entries() to loop through it while keeping track of each fruit's position.

In short, getting the indexes while using for...of loops lets you do more with your collections in JavaScript. It's great for when you want to keep things in order or map positions to what you're storing.

Best Practices

When you're using for...of loops to go through items in JavaScript and you also want to keep track of where each item is in the list (its index), here are some handy tips to keep in mind:

Know When Indexes Are Needed

  • Only bother with indexes if you're planning to change the order of items or need to match each item with specific data.
  • If you're just looking at the items and not changing them, you probably don't need the indexes.

Use .entries() for Simplicity

  • The .entries() method is great because it gives you both the item and its place in the list right away. This means you don't have to do extra work to find out these details.
  • It's also easy to understand and use, making it a good choice for most situations.

Lean on .keys() for Performance

  • If you're dealing with a really big list, .keys() might work better because it's faster.
  • Since it doesn't bother with the items themselves, it also doesn't use as much memory.

Cache Length for Optimization

// Cache length
const length = array.length
for (let [index] of array.entries()) {
  if (index === length - 1) {
    // Last item actions
  }
}
  • Remembering the list's length ahead of time can make things faster because you're not checking the length every time in the loop.

Avoid Updating Original Array

  • Changing the list while you're going through it can lead to mistakes.
  • It's safer to make changes to a separate list:
const updated = []
for (let [index, item] of array.entries()) {
  // Modify item
  updated.push(item)
}

Use Breaks and Continues Carefully

  • Using break and continue can mess up the flow of your loop in ways you might not expect.
  • Make sure you really know what you're doing before you use them.

By keeping these tips in mind, you'll be able to use for...of loops with indexes more effectively, while dodging some common mistakes. The main thing is to think about whether you really need those indexes or if just going through the items is enough.

Conclusion

Knowing how to use indexes in for...of loops is super useful when you're coding in JavaScript. Let's go over the main points:

  • The entries() method gives you both the index and the value for each item in your loop. It's straightforward to use but might slow things down if you're working with a lot of data.
  • The keys() method only gives you the indexes. It could be faster, but you'll need to do an extra step to get the values.
  • If you remember the length of the array before starting the loop, you can make your code run faster. This is because you're not asking the computer to figure out the length over and over again.
  • Changing the original array while looping through it can lead to problems. It's usually a better idea to create a new array for any changes you want to make.
  • Be careful with using break and continue. They can make your loop do unexpected things, so make sure you really need them before adding them in.

Whether you should use entries() or keys() depends on if you need to know both the index and value at the same time, or if you're trying to speed things up. Generally, entries() is easier unless you're dealing with big data.

Getting good at using indexes can help you sort arrays, link values with their positions, keep things in order, and more. It's a key part of making your JavaScript code work well.

So, practice using for...of loops with entries() and keys() until you're comfortable. This skill is really handy as you get better at JavaScript.

What is index of for JavaScript?

The indexOf() method in JavaScript is a way to find out where a certain piece of text starts within a bigger text. For instance, if you want to know where the letter "o" first appears in the word "Hello", indexOf() can tell you it's at position 4 (counting starts from 0).

Here's a quick example:

let str = "Hello world";

str.indexOf("o"); // 4
str.indexOf("o", 6); // 7

So, indexOf() helps you find where a certain word or letter is in a sentence or a bigger piece of text.

What is the use of index in JavaScript?

Indexes in JavaScript are super useful for a few reasons:

  • Getting to things in a list - If you have a list (or an array) of items, you use an index to grab specific things out of that list. For example, array[0] gets you the first item.

  • Finding spots in text - When you're working with words or sentences (strings), indexes help you point to specific spots.

  • Looping through stuff - When you're going over items in a list one by one, indexes help you keep track of where you are.

  • Organizing data - You can use indexes as keys in objects to store and find data easily.

Basically, indexes help you manage and access data more efficiently, whether that's in lists, texts, or when you're keeping track of your loops.

What is the use of for of loop in JavaScript?

The for...of loop in JavaScript is great for going over items in a list like arrays or strings, or even more complex stuff like maps and sets. It lets you run some code for each item in that list. Here's how you might use it:

let arr = [1, 2, 3];
for (let a of arr) {
  console.log(a); 
}

It's a handy tool because it saves you from having to mess with indexes if you don't need them. It makes your code cleaner and easier to read when you're just looking at the items in a list.

How to use forEach with index in JavaScript?

The forEach() method is like a loop that automatically goes over each item in a list, and it gives you both the item and its position (index) right away. Here's an example:

let arr = ['a', 'b', 'c'];

arr.forEach((element, index) => {
  console.log(index + '. ' + element);  
});

// 0. a
// 1. b 
// 2. c

This is a simple way to work with both the items and their positions without having to do extra work to keep track of the index. It's pretty straightforward and keeps your code clean.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more