How can I loop through all the entries in an array using JavaScript?
I thought it was something like this:
forEach(instance in theArray)
Where theArray
is my array, but this seems to be incorrect.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
TL;DR
for-of
loop (ES2015+ only; spec | MDN) – simple andasync
-friendlyforEach
(ES5+ only; spec | MDN) (or its relativessome
and such) – notasync
-friendly (but see details)for
loop –async
-friendlyfor-in
with safeguards –async
-friendlyfor-in
unless you use it with safeguards or are at least aware of why it might bite you.map
if you’re not using its return value.(There’s sadly someone out there teaching
map
[spec / MDN] as though it wereforEach
— but as I write on my blog, that’s not what it’s for. If you aren’t using the array it creates, don’t usemap
.)forEach
if the callback does asynchronous work and you want theforEach
to wait until that work is done (because it won’t).But there’s lots more to explore, read on…
JavaScript has powerful semantics for looping through arrays and array-like objects. I’ve split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the
arguments
object, other iterable objects (ES2015+), DOM collections, and so on.Okay, let’s look at our options:
For Actual Arrays
You have five options (two supported basically forever, another added by ECMAScript 5 [“ES5”], and two more added in ECMAScript 2015 (“ES2015”, aka “ES6”):
for-of
(use an iterator implicitly) (ES2015+)forEach
and related (ES5+)for
loopfor-in
correctly(You can see those old specs here: ES5, ES2015, but both have been superceded; the current editor’s draft is always here.)
Details:
1. Use
for-of
(use an iterator implicitly) (ES2015+)ES2015 added iterators and iterables to JavaScript. Arrays are iterable (so are strings,
Map
s, andSet
s, as well as DOM collections and lists, as you’ll see later). Iterable objects provide iterators for their values. The newfor-of
statement loops through the values returned by an iterator: