Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Yaser Adel Mehraban
Yaser Adel Mehraban

Posted on • Originally published atyashints.dev

     

Have you ever thought about different types of for loops? ➰

Using a loop is almost a must in our day to day life. But have you ever thought what kind of loop should you use? Do you know the difference between enumerables and iterables? This article sheds some light in this space, so read on if you're interested.

Background

Looping has seen quite a few changes from when I started programming. I remember using while loops and thinking wow, this is cool (I was printing starts on console using MS-DOS).

For loop is another way to iterate through a data structure which contains many items. But non of these methods iterate over the actual structure. They use a sequence, usually namedi which mirrors the identifier for you.

constfruits=['🍉','🍎','🍌'];for(leti=0;i<fruits.length;i++){console.log(fruits[i]);}// 🍉, 🍎, 🍌
Enter fullscreen modeExit fullscreen mode

Herei is an index which allows you to access the elements of fruits array and is not part of the array itself. But with progress onJavaScript towards more modern ways of programming, things have changes now. We havefor...in, andfor...of loops which use a different mechanism for going through items in a collection.

Concepts

Before we delve into these newer ways of iteration, we need to be on the same page around some concepts. So let's go through them now:

  • Iterables: This is a kind of loop where we are performing a repetition. Meaning the same set of actions are performed on each item.
  • Enumerables: This is a kind of loop where we making mention of, or counting items one at a time. This means the collection's elements can be distinctly identified and referenced.

That didn't click for me at first, but after going through some examples, it finally made sense. If you consider afull pencil case, that's an enumerable. When youline up at Aldi to pay, that line is an iterable. Awad of cash is an enumerable, whereas arow of keys on your keyboard is an iterable.

💡 In order for an object to beiterable, it MUST implement an@@iterator property which returns an iterator. An iterator object is one which has anext method which returns the next item in the collection. That's why an object is not an iterable.

By now you should have started to see the pattern here. The best analogy I came across is:

😍Enumerables are like rectangles whereasiterables are squares. This means alliterables areenumerables, however, not allenumerables areiterables.

for...in

So let's start fromenumerables. You can go through enumerables usingfor...in. The use case is mainly to go through key-value pairs in an object:

constsuperCar={make:'Lamborghini',model:'Veneno',year:'2020'};for(letkeyinsuperCar){console.log(`${key} -->${superCar[key]}`);}// make --> Lamborghini// model --> Veneno// year --> 2020
Enter fullscreen modeExit fullscreen mode

You can also usefor...in to go through index values of an iterable like an array or a string:

letfact='Lamborghini is the best!';for(letindexinfact){console.log(`Index of${fact[index]}:${index}`);}// Index of L: 0// Index of a: 1// Index of m: 2// Index of b: 3// ...
Enter fullscreen modeExit fullscreen mode

💡 Beware that you can't iterate onSymbol properties withfor...in and that's becauseSymbols are primitive data types that arealways unique. They are generally used as private properties to avoid name clashes when inheritance is used.

Usingfor...of

This kind of loop is applicable to "iterable objects" meaning the item afterof MUST be aniterable:

constfruits=['🍉','🍎','🍌'];for(letfruitoffruits){console.log(`${fruit} is delicious.`);}// 🍉 is delicious.// 🍎 is delicious.// 🍌 is delicious.
Enter fullscreen modeExit fullscreen mode

And again we can use it on strings, but with a slight difference:

letfact='Yas';for(letcharoffact){console.log(char);}// Y// a// s
Enter fullscreen modeExit fullscreen mode

Summary

We saw the difference between these two modern ways of looping through collections, let's make more informed decisions as to use what where and write cleaner, more readable code 👊🏽.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
delta456 profile image
Swastik Baranwal
Open Source Engineer

Javascript has so many of them! Thanks for making this post!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Azure Technical Trainer @Microsoft, almond croissant addict cleverly disguised as a web developer
  • Location
    Melbourne, Australia
  • Education
    Master’s Information Security
  • Work
    Azure Technical Trainer at Microsoft
  • Joined

More fromYaser Adel Mehraban

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp