Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of

This blog post compares four ways of looping over Arrays:

The for loop:
for (let index=0; index < someArray.length; index++) {
const elem = someArray[index];
// ···
}

The for-in loop:
for (const key in someArray) {
console.log(key);
}


This content originally appeared on 2ality – JavaScript and more and was authored by Dr. Axel Rauschmayer

This blog post compares four ways of looping over Arrays:

  • The for loop:

    for (let index=0; index < someArray.length; index++) {
      const elem = someArray[index];
      // ···
    }
    
  • The for-in loop:

    for (const key in someArray) {
      console.log(key);
    }
    
  • The Array method .forEach():

    someArray.forEach((elem, index) => {
      console.log(elem, index);
    });
    
  • The for-of loop:

    for (const elem of someArray) {
      console.log(elem);
    }
    

for-of is often the best choice. We’ll see why.

[Read rest of post]


This content originally appeared on 2ality – JavaScript and more and was authored by Dr. Axel Rauschmayer


Print Share Comment Cite Upload Translate Updates
APA

Dr. Axel Rauschmayer | Sciencx (2021-01-07T00:00:00+00:00) Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of. Retrieved from https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/

MLA
" » Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of." Dr. Axel Rauschmayer | Sciencx - Thursday January 7, 2021, https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/
HARVARD
Dr. Axel Rauschmayer | Sciencx Thursday January 7, 2021 » Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of., viewed ,<https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/>
VANCOUVER
Dr. Axel Rauschmayer | Sciencx - » Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/
CHICAGO
" » Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of." Dr. Axel Rauschmayer | Sciencx - Accessed . https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/
IEEE
" » Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of." Dr. Axel Rauschmayer | Sciencx [Online]. Available: https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/. [Accessed: ]
rf:citation
» Looping over Arrays: for vs. for-in vs. .forEach() vs. for-of | Dr. Axel Rauschmayer | Sciencx | https://www.scien.cx/2021/01/07/looping-over-arrays-for-vs-for-in-vs-foreach-vs-for-of/ |

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.