Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jacob Paris
Jacob Paris

Posted on

     

How To For Loop Through Anything in JS

There are now four ways to open a for loop in javascript

  • For of
  • For await of
  • For in
  • Classic For

While they differ a bit on speed and the variables they declare implicitly, the actual body of the for loop doesn't change much between the different methods.

The easiest way to loop through an array is with the for…of loop

constfruits=['apple','banana','cherry']for(constfruitoffruits){console.log(fruit)}// apple// banana// cherry
Enter fullscreen modeExit fullscreen mode

We're not limited to arrays though, since all iterators work the same in javascript. That means we can just as easily loop through a string

for(constletterof"javascript"){console.log(letter)}// j// a// v// a// s// c// r// i// p// t
Enter fullscreen modeExit fullscreen mode

Many emojis are stored as multiple codepoints, and some emojis are created by joining multiple other emojis.

For…of will iterate over them one by return, returning every 👨 in a 👨‍👩‍👧‍👦

for(constpersonof"👨‍👩‍👧‍👦"){console.log(person)}// 👨// 👩// 👧// 👦
Enter fullscreen modeExit fullscreen mode

We can use thereturn keyword to break out of a function early. In a loop, we can use thecontinue keyword to break out of the current iteration and start the next iteration immediately.

constsequence=[0,1,2,3,4,5]for(constnumberofsequence){if(isOdd(number))continueconsole.log(number)}// 0// 2// 4
Enter fullscreen modeExit fullscreen mode

Loops also have thebreak keyword, which will cancel not only the current iteration but also the rest of the loop

constsequence=[0,1,2,3,4,5]for(constnumberofsequence){if(number>=3)breakconsole.log(number)}// 0// 1// 2
Enter fullscreen modeExit fullscreen mode

At the end of every iteration, the current scope is discarded and a new one is opened, so it's ok to useconst orlet at the start

for(constitemofitems)// orfor(letitemofitems)
Enter fullscreen modeExit fullscreen mode

If you try to useawait inside a loop, the execution will pause until the promise resolves and then it'll proceed as usual. To allow the loops to proceed concurrently, you can either await the promises before starting the loop or usingfor await of to do the same thing

for(constxofawaitPromise.all(arrayOfPromises))// orforawait(constxofarrayOfPromises)
Enter fullscreen modeExit fullscreen mode

In javascript, objects are not strictly iterable. If you want to loop through the keys of an object, you can either usefor in or convert the keys to an array

consthashMap={abcd:{},abce:{},abcf:{},abcg:{},abch:{}}
Enter fullscreen modeExit fullscreen mode
for(constkeyofObject.keys(hashMap)){constvalue=hashMap[key]}// orfor(constkeyinhashMap){constvalue=hashMap[key]}
Enter fullscreen modeExit fullscreen mode

If the only thing we need the key for is to access the value, we can skip a step and loop through the values directly

for(constvalueofObject.values(hashMap){}
Enter fullscreen modeExit fullscreen mode

If we need both key and value, my preferred method is to useObject.entries, which returns a[key, value] pair, and destructure them right in the head the loop

for(const[key,value]ofObject.entries(hashMap)){}
Enter fullscreen modeExit fullscreen mode

Since arrays are just objects with numeric keys, we can use that same syntax to get the index of our array elements inside our loop

for(const[i,element]ofObject.entries(array)){}
Enter fullscreen modeExit fullscreen mode

To run a loop a specific number of times, we can create an array with that many elements and then loop through it.

Iterators skip over empty array slots, so we need to fill it with at least undefined first, and then optionally map its index

constarray=Array(25).fill()// [ empty, empty, empty, …]// orconstarray=Array(25).fill().map((_,i)=>i)// [ 0, 1, 2, … ]for(constiofarray){}
Enter fullscreen modeExit fullscreen mode

The other option is to use the classic for loop syntax. This gives you the most control at the cost of readability.

for(leti;i<25;i++){}
Enter fullscreen modeExit fullscreen mode

Top comments(7)

Subscribe
pic
Create template

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

Dismiss
CollapseExpand
 
fleshmecha profile image
Web performance and multi page applications.
  • Work
    Front End Developer
  • Joined

I really hoped this was going to tell me how to write the fastest for loop! Which one is quickest?

CollapseExpand
 
patarapolw profile image
Pacharapol Withayasakpunt
Currently interested in TypeScript, Vue, Kotlin and Python. Looking forward to learning DevOps, though.
  • Location
    Thailand
  • Education
    Yes
  • Joined
• Edited on• Edited

jsperf.com/loop-vs-map-vs-foreach/22

So,map and classical for loop. But it is usually more semantically to useforEach rather thanmap, albeit slow.

for loop isn't so bad, but it depends on the use case.

CollapseExpand
 
leob profile image
leob
  • Joined

Why is it more semantical to write "arr.forEach(...)" instead of "for (... of arr)" ? Seems merely a matter of syntax and taste to me ...

Thread Thread
 
jacobmparis profile image
Jacob Paris
Sales funnels and B2B SaaS for the mortgage industry, almond latte fanatic, LA @eggheadio , formerly ToolStache
  • Location
    Toronto, ON
  • Work
    Senior Developer at Fintech
  • Joined

I would absolutely consider this to be a matter of taste

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt
Currently interested in TypeScript, Vue, Kotlin and Python. Looking forward to learning DevOps, though.
  • Location
    Thailand
  • Education
    Yes
  • Joined

I meantarr.forEach() vsarr.map().

for of andfor in are another species, and is whether you want it to be functional or procedural. Neither is better than the others.

CollapseExpand
 
jacobmparis profile image
Jacob Paris
Sales funnels and B2B SaaS for the mortgage industry, almond latte fanatic, LA @eggheadio , formerly ToolStache
  • Location
    Toronto, ON
  • Work
    Senior Developer at Fintech
  • Joined

That depends what you're measuring

Most of the time a for loop takes up is spent doing logic on each iteration. The amount of time it takes to switch from the end of one iteration to another (which is the only way these differ) is microscopic in comparison.

Unless you're doing many thousands of iterations, performance is the wrong heuristic to help you decide

CollapseExpand
 
leob profile image
leob
  • Joined

Great article, thorough and informative, the kind of content that seems to become increasingly rare on dev.to ...

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

Sales funnels and B2B SaaS for the mortgage industry, almond latte fanatic, LA @eggheadio , formerly ToolStache
  • Location
    Toronto, ON
  • Work
    Senior Developer at Fintech
  • Joined

More fromJacob Paris

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