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.
This content originally appeared on 2ality – JavaScript and more and was authored by Dr. Axel Rauschmayer
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.