For-each over an array in JavaScript
TL;DR
Your best bets are usually
- a
for-of
loop (ES2015+ only; spec | MDN) - simple andasync
-friendlyfor (const element of theArray) {
// ...use `element`...
} forEach
(ES5+ only; spec | MDN) (or its relativessome
and such) - notasync
-friendly (but see details)theArray.forEach(element => {
// ...use `element`...
});- a simple old-fashioned
for
loop -async
-friendlyfor (let index = 0; index < theArray.length; ++index) {
const element = theArray[index];
// ...use `element`...
} - (rarely)
for-in
with safeguards -async
-friendlyfor (const propertyName in theArray) {
if (/*...is an array element property (see below)...*/) {
const element = theArray[propertyName];
// ...use `element`...
}
}
- a
Some quick "don't"s:
- Don't use
for-in
unless you use it with safeguards or are at least aware of why it might bite you. - Don't use
map
if you're not using its return value.
(There's sadly someone out there teachingmap
[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
.) - Don't use
forEach
if the callback does asynchronous work and you want theforEach
to wait until that work is done (because it won't).
- Don't use
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"):
- Use
for-of
(use an iterator implicitly) (ES2015+) - Use
forEach
and related (ES5+) - Use a simple
for
loop - Use
for-in
correctly - Use an iterator explicitly (ES2015+)
(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, and Set
s, as well as DOM collections and lists, as you'll see later). Iterable objects provide iterators for their values. The new for-of
statement loops through the values returned by an iterator:
const a = ["a", "b", "c"];
for (const element of a) { // You can use `let` instead of `const` if you like
console.log(element);
}
// a
// b
// c
Javascript: How to loop through every array's item every second
You can use an interval.
Here is an example:
var arr = [0,1,2,3,4];
var index = 0;
setInterval(function(){
console.log(arr[index++ % arr.length]);
}, 1000)
How to loop through an array containing objects and access their properties
Use forEach its a built-in array function. Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
What's the fastest way to loop through an array in JavaScript?
After performing this test with most modern browsers:
https://jsben.ch/wY5fo
Currently, the fastest form of loop (and in my opinion the most syntactically obvious).
A standard for-loop with length caching
var i = 0, len = myArray.length;
while (i < len) {
// your code
i++
}
I would say, this is definitely a case where I applaud JavaScript engine developers. A runtime should be optimized for clarity, not cleverness.
Loop through Array and return result into Array
You can use forEach
function, which accepts a callback
function.
forEach
method executes a provided function once for each array element.
Syntax:
arr.forEach(function callback(currentValue, index, array) {
}[, thisArg]);
var shareholders = ['name1', 'name2', 'name3'];
var users=new Array();
shareholders.forEach(function(item,i){
users[i]=item;
});
console.log(users);
Why is using for...in for array iteration a bad idea?
The reason is that one construct:
var a = []; // Create a new empty array.
a[5] = 5; // Perfectly legal JavaScript that resizes the array.
for (var i = 0; i < a.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
console.log(a[i]);
}
/* Will display:
undefined
undefined
undefined
undefined
undefined
5
*/
loop through array of objects and get all object values as a single string
You can use map and join like this
const arr = [
{ id: 1, value: "Apple" },
{ id: 1, value: "Orange" },
{ id: 1, value: "Pine Apple" },
{ id: 1, value: "Banana" },
];
const result = arr.map(({ value }) => value).join(', ')
console.log(result)
Loop through an array by set of 4 elements at a time in Javascript?
Use a for loop where i increases by 4.
Note: I was working on my answer when Jaromanda X commented the same thing.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
for (var i = 0; i < arr.length; i += 4) {
console.log("Working with: " + arr.slice(i, i + 4));
}
Related Topics
How to Sort an Object Array by Date Property
Getting a Random Value from a JavaScript Array
Weird Behavior With Objects & Console.Log
When Is .Then(Success, Fail) Considered an Antipattern For Promises
Share Data Between Angularjs Controllers
JavaScript by Reference Vs. by Value
Send Post Data Using Xmlhttprequest
Creating a Blob from a Base64 String in JavaScript
How to Pad a Value With Leading Zeros
Short Circuit Array.Foreach Like Calling Break
JavaScript Object: Access Variable Property by Name as String
Http Get Request in JavaScript
Get Difference Between 2 Dates in JavaScript
When Is JavaScript'S Eval() Not Evil
Onclick or Inline Script Isn't Working in Extension
How to Get Client'S Ip Address Using JavaScript