Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
For-each over an array in JavaScript

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.

over 4 years ago Β· Santiago Trujillo
33 answers
Answer question

0

As per the new updated feature ECMAScript 6 (ES6) and ECMAScript 2015, you can use the following options with loops:

for loops

for(var i = 0; i < 5; i++){
  console.log(i);
}

// Output: 0,1,2,3,4

for...in loops

let obj = {"a":1, "b":2}

for(let k in obj){
  console.log(k)
}

// Output: a,b

Array.forEach()

let array = [1,2,3,4]

array.forEach((x) => {
  console.log(x);
})

// Output: 1,2,3,4

for...of loops

let array = [1,2,3,4]

for(let x of array){
  console.log(x);
}

// Output: 1,2,3,4

while loops

let x = 0

while(x < 5){
  console.log(x)
  x++
}

// Output: 1,2,3,4

do...while loops

let x = 0

do{
  console.log(x)
  x++
}while(x < 5)

// Output: 1,2,3,4
over 4 years ago Β· Santiago Trujillo Report

0

Suppose we have an array of subjects:

let ddl = new Array();
if (subjects) {
    subjects.forEach(function (s) {ddl.push({"id": s.id, "label": s.name});});
}
over 4 years ago Β· Santiago Trujillo Report

0

for...of   |   forEach   |   map

Using modern JavaScript syntax to iterate through arrays

const fruits = ['🍎', 'πŸ‹', '🍌' ]

πŸ‘‰πŸ½ Β  for...of

for (const fruit of fruits) {
    console.log(fruit)  // '🍎', 'πŸ‹', '🍌'
}

πŸ‘‰πŸ½ Β  forEach

fruits.forEach(fruit => {
    console.log(fruit)  // '🍎', 'πŸ‹', '🍌'
})

πŸ‘‰πŸ½ Β  map

*Different from the two above, map() creates a new array and expects you to return something after each iteration.

fruits.map(fruit => fruit)   // ['🍎', 'πŸ‹', '🍌' ]

πŸ›‘Β  Important: As map() is meant to return a value at each iteration, it is an ideal method for transforming elements in arrays:

fruits.map(fruit => 'cool ' + fruit)   // ['cool 🍎', 'cool πŸ‹', 'cool 🍌' ]

On the other hand, for...of and forEach( ) don't need to return anything and that's why we typically use them to perform logic tasks that manipulate stuff outside.

So to speak, you're going to find if () statements, side effects, and logging activities in these two.

πŸ‘ŒπŸΎΒ  TIP: you can also have the index (as well as the whole array) in each iteration in your .map() or .forEach() functions.

Just pass additional arguments to them:

fruits.map((fruit, i) =>  i + '  ' + fruit)

// ['0 🍎', '1 πŸ‹', '2 🍌' ]

fruits.forEach((f, i, arr) => {
    console.log( f + ' ' + i + ' ' +  arr )
})

// 🍎  0  🍎, πŸ‹, 🍌,
// πŸ‹  1  🍎, πŸ‹, 🍌,
// 🍌  2  🍎, πŸ‹, 🍌,
over 4 years ago Β· Santiago Trujillo Report

0

Try:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];
over 4 years ago Β· Santiago Trujillo Report

0

I come from Python, and I found this way much clearer.

theArray being the array, and instance being the elements of the array:

for (let instance of theArray)
{
    console.log("The instance", instance);
}

or

for (instance in theArray)
{
    console.log("The instance", instance);
}

compare to:

theArray.forEach(function(instance) {
    console.log(instance);
});

But at the end of the day both are doing the same thing.

over 4 years ago Β· Santiago Trujillo Report

0

// Looping through arrays using the foreach ECMAScript 6 way

var data = new Array(1, 2, 3, 4, 5);
data.forEach((val,index) => {
    console.log("index: ", index); // Index
    console.log("value: ", val); // Value
});

over 4 years ago Β· Santiago Trujillo Report

0

If you want to keep your code in the functional way, use map:

theArray.map(instance => do_something);

In this way you will generate a new array to future operation and will skip any not desirable side effect.

over 4 years ago Β· Santiago Trujillo Report

0

If you want to loop through an array of objects with the arrow function:

let arr = [{name:'john', age:50}, {name:'clark', age:19}, {name:'mohan', age:26}];

arr.forEach((person)=>{
  console.log('I am ' + person.name + ' and I am ' + person.age + ' old');
})

over 4 years ago Β· Santiago Trujillo Report

0

Mozilla documentation

/* Get all forms */
document.querySelectorAll( "form" ).forEach( form => {

  /* For each form, add the onsubmit event */
  form.addEventListener( "submit", event => {
    event.preventDefault(); // Return false

    /* Display it */
    alert(event.target.action);
    console.log(event.target);
  } );

} );
<form action="form1.php" >
  <input type="submit" value="Submit" />
</form>
<form action="form2.php" >
  <input type="submit" value="Submit" />
</form>
<form action="form3.php" >
  <input type="submit" value="Submit" />
</form>

over 4 years ago Β· Santiago Trujillo Report

0

You can use:

  1. ForEach

    theArray.forEach(function (array, index) {
        console.log(index);
        console.log(array);
    });
    
  2. for

    for(var i=0; i<theArray.length; i++) {
        console.log(i)
    }
    
  3. map

    theArray.map(x => console.log(x));
    
  4. map

    theArray.filter(x => console.log(x));
    

And there are many others for iteration.

over 4 years ago Β· Santiago Trujillo Report

0

I'd argue that for/of is the way to go:

const arr = ['a', 'b', 'c'];

for (const v of arr) {
  console.log(v); // Prints "a", "b", "c"
}

  • Unlike for/in, for/of skips non-numeric properties on the array. For example, if you set arr.foo = 'test', for (var v in arr) will loop through the 'foo' key.

  • Unlike forEach(), for/of doesn't skip "holes" in arrays. const arr = ['a',, 'c'] is valid JavaScript, just the 2nd element is a "hole". The array is functionally equivalent to ['a', undefined, 'c'].

You can read more in this blog post on for/of vs forEach().

over 4 years ago Β· Santiago Trujillo Report

0

As of ECMAScript 6:

list = [0, 1, 2, 3]
for (let obj of list) {
    console.log(obj)
}

Where of avoids the oddities associated with in and makes it work like the for loop of any other language, and let binds i within the loop as opposed to within the function.

The braces ({}) can be omitted when there is only one command (e.g. in the example above).

over 4 years ago Β· Santiago Trujillo Report

0

A way closest to your idea would be to use Array.forEach() which accepts a closure function which will be executed for each element of the array.

myArray.forEach(
  (item) => {
    // Do something
    console.log(item);
  }
);

Another viable way would be to use Array.map() which works in the same way, but it also takes all values that you return and returns them in a new array (essentially mapping each element to a new one), like this:

var myArray = [1, 2, 3];
myArray = myArray.map(
  (item) => {
    return item + 1;
  }
);

console.log(myArray); // [2, 3, 4]
over 4 years ago Β· Santiago Trujillo Report

0

The lambda syntax doesn't usually work in Internet Explorer 10 or below.

I usually use the

[].forEach.call(arrayName,function(value,index){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});

If you are a jQuery fan and already have a jQuery file running, you should reverse the positions of the index and value parameters

$("#ul>li").each(function(**index, value**){
    console.log("value of the looped element" + value);
    console.log("index of the looped element" + index);
});
over 4 years ago Β· Santiago Trujillo Report

0

ECMAScript 5 (the version on JavaScript) to work with Arrays:

forEach - Iterates through every item in the array and do whatever you need with each item.

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is #" + (index+1) + " in the musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

In case, more interested on operation on array using some inbuilt feature.

map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

reduce - As the name says, it reduces the array to a single value by calling the given function passing in the current element and the result of the previous execution.

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});
// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

every - Returns true or false if all the elements in the array pass the test in the callback function.

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];
ages.every(function(elem) {
  return elem >= 18;
});

// Output: false

filter - Very similar to every except that filter returns an array with the elements that return true to the given function.

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]
over 4 years ago Β· Santiago Trujillo Report

0

There are a few ways to loop through an array in JavaScript, as below:

for - it's the most common one. Full block of code for looping

var languages = ["Java", "JavaScript", "C#", "Python"];
var i, len, text;
for (i = 0, len = languages.length, text = ""; i < len; i++) {
    text += languages[i] + "<br>";
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

while - loop while a condition is through. It seems to be the fastest loop

var text = "";
var i = 0;
while (i < 10) {
    text +=  i + ") something<br>";
    i++;
}
document.getElementById("example").innerHTML = text;
<p id="example"></p>

do/while - also loop through a block of code while the condition is true, will run at least one time

var text = ""
var i = 0;

do {
    text += i + ") something <br>";
    i++;
}
while (i < 10);

document.getElementById("example").innerHTML = text;
<p id="example"></p>

Functional loops - forEach, map, filter, also reduce (they loop through the function, but they are used if you need to do something with your array, etc.

// For example, in this case we loop through the number and double them up using the map function
var numbers = [65, 44, 12, 4];
document.getElementById("example").innerHTML = numbers.map(function(num){return num * 2});
<p id="example"></p>

For more information and examples about functional programming on arrays, look at the blog post Functional programming in JavaScript: map, filter and reduce.

over 4 years ago Β· Santiago Trujillo Report

0

var a = ["car", "bus", "truck"]
a.forEach(function(item, index) {
    console.log("Index" + index);
    console.log("Element" + item);
})
over 4 years ago Β· Santiago Trujillo Report

0

If you want to use forEach(), it will look like -

theArray.forEach ( element => {
    console.log(element);
});

If you want to use for(), it will look like -

for(let idx = 0; idx < theArray.length; idx++){
    let element = theArray[idx];
    console.log(element);
}
over 4 years ago Β· Santiago Trujillo Report

0

You can call forEach like this:

forEach will iterate over the array you provide and for each iteration it will have element which holds the value of that iteration. If you need index you can get the current index by passing the i as the second parameter in the callback function for forEach.

Foreach is basically a High Order Function, Which takes another function as its parameter.

let theArray= [1,3,2];

theArray.forEach((element) => {
  // Use the element of the array
  console.log(element)
}

Output:

1
3
2

You can also iterate over an array like this:

for (let i=0; i<theArray.length; i++) {
  console.log(i); // i will have the value of each index
}
over 4 years ago Β· Santiago Trujillo Report

0

If you don't mind emptying the array:

var x;

while(x = y.pop()){ 

    alert(x); //do something 

}

x will contain the last value of y and it will be removed from the array. You can also use shift() which will give and remove the first item from y.

over 4 years ago Β· Santiago Trujillo Report

0

A forEach implementation (see in jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);
over 4 years ago Β· Santiago Trujillo Report

0

Note: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:

  • forEach
  • map
  • filter
  • zip
  • reduce
  • every
  • some

The standard way to iterate an array in JavaScript is a vanilla for-loop:

var length = arr.length,
    element = null;
for (var i = 0; i < length; i++) {
  element = arr[i];
  // Do something with element
}

Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a for .. in-loop might be a better idea. However, you must use the appropriate safeguards to ensure that only the desired properties of the array (that is, the array elements) are acted upon, since the for..in-loop will also be enumerated in legacy browsers, or if the additional properties are defined as enumerable.

In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include.

over 4 years ago Β· Santiago Trujillo Report

0

If you want to loop over an array, use the standard three-part for loop.

for (var i = 0; i < myArray.length; i++) {
    var arrayItem = myArray[i];
}

You can get some performance optimisations by caching myArray.length or iterating over it backwards.

over 4 years ago Β· Santiago Trujillo Report

0

There isn't any for each loop in native JavaScript. You can either use libraries to get this functionality (I recommend Underscore.js), use a simple for in loop.

for (var instance in objects) {
   ...
}

However, note that there may be reasons to use an even simpler for loop (see Stack Overflow question Why is using β€œfor…in” with array iteration such a bad idea?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];
    ...
}
over 4 years ago Β· Santiago Trujillo Report

0

Some C-style languages use foreach to loop through enumerations. In JavaScript this is done with the for..in loop structure:

var index,
    value;
for (index in obj) {
    value = obj[index];
}

There is a catch. for..in will loop through each of the object's enumerable members, and the members on its prototype. To avoid reading values that are inherited through the object's prototype, simply check if the property belongs to the object:

for (i in obj) {
    if (obj.hasOwnProperty(i)) {
        //do stuff
    }
}

Additionally, ECMAScript 5 has added a forEach method to Array.prototype which can be used to enumerate over an array using a calback (the polyfill is in the docs so you can still use it for older browsers):

arr.forEach(function (val, index, theArray) {
    //do stuff
});

It's important to note that Array.prototype.forEach doesn't break when the callback returns false. jQuery and Underscore.js provide their own variations on each to provide loops that can be short-circuited.

over 4 years ago Β· Santiago Trujillo Report

0

If you’re using the jQuery library, you can use jQuery.each:

$.each(yourArray, function(index, value) {
  // do your stuff here
});

EDIT :

As per question, user want code in javascript instead of jquery so the edit is

var length = yourArray.length;   
for (var i = 0; i < length; i++) {
  // Do something with yourArray[i].
}
over 4 years ago Β· Santiago Trujillo Report

0

I also would like to add this as a composition of a reverse loop and an answer above for someone that would like this syntax too.

var foo = [object,object,object];
for (var i = foo.length, item; item = foo[--i];) {
    console.log(item);
}

Pros:

The benefit for this: You have the reference already in the first like that won't need to be declared later with another line. It is handy when looping trough the object array.

Cons:

This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. And also depending on the browser it can be "not" optimized to work faster than the original one.

over 4 years ago Β· Santiago Trujillo Report

0

There's no inbuilt ability to break in forEach. To interrupt execution use the Array#some like below:

[1,2,3].some(function(number) {
    return number === 1;
});

This works because some returns true as soon as any of the callbacks, executed in array order, returns true, short-circuiting the execution of the rest. Original Answer see Array prototype for some

over 4 years ago Β· Santiago Trujillo Report

0

This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)

function each( fn, data ) {

    if(typeof fn == 'string')
        eval('fn = function(data, i){' + fn + '}');

    for(var i=0, L=this.length; i < L; i++) 
        fn.call( this[i], data, i );   

    return this;
}

Array.prototype.each = each;  

Examples of usage:

Example #1

var arr = [];
[1, 2, 3].each( function(a){ a.push( this * this}, arr);
arr = [1, 4, 9]

Example #2

each.call(document.getElementsByTagName('p'), "this.className = data;",'blue');

Each p tag gets class="blue"

Example #3

each.call(document.getElementsByTagName('p'), 
    "if( i % 2 == 0) this.className = data;",
    'red'
);

Every other p tag gets class="red">

Example #4

each.call(document.querySelectorAll('p.blue'), 
    function(newClass, i) {
        if( i < 20 )
            this.className = newClass;
    }, 'green'
);

And finally the first 20 blue p tags are changed to green

Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive.

over 4 years ago Β· Santiago Trujillo Report

0

There are three implementations of foreach in jQuery as follows.

var a = [3,2];

$(a).each(function(){console.log(this.valueOf())}); //Method 1
$.each(a, function(){console.log(this.valueOf())}); //Method 2
$.each($(a), function(){console.log(this.valueOf())}); //Method 3
over 4 years ago Β· Santiago Trujillo Report

0

jQuery way using $.map:

var data = [1, 2, 3, 4, 5, 6, 7];

var newData = $.map(data, function(element) {
    if (element % 2 == 0) {
        return element;
    }
});

// newData = [2, 4, 6];
over 4 years ago Β· Santiago Trujillo Report

0

An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as each and will automatically delegate the job to the native forEach if available.

A CodePen example of how it works is:

var arr = ["elemA", "elemB", "elemC"];
_.each(arr, function(elem, index, ar)
{
...
});

See also

  • Documentation for native Array.prototype.forEach().
  • In for_each...in (MDN) it is explained that for each (variable in object) is deprecated as the part of ECMA-357 (EAX) standard.
  • for...of (MDN) describes the next way of iterating using for (variable of object) as the part of the Harmony (ECMAScript 6) proposal.
over 4 years ago Β· Santiago Trujillo Report

0

Probably the for(i = 0; i < array.length; i++) loop is not the best choice. Why? If you have this:

var array = new Array();
array[1] = "Hello";
array[7] = "World";
array[11] = "!";

The method will call from array[0] to array[2]. First, this will first reference variables you don't even have, second you would not have the variables in the array, and third this will make the code bolder. Look here, it's what I use:

for(var i in array){
    var el = array[i];
    //If you want 'i' to be INT just put parseInt(i)
    //Do something with el
}

And if you want it to be a function, you can do this:

function foreach(array, call){
    for(var i in array){
        call(array[i]);
    }
}

If you want to break, a little more logic:

function foreach(array, call){
    for(var i in array){
        if(call(array[i]) == false){
            break;
        }
    }
}

Example:

foreach(array, function(el){
    if(el != "!"){
        console.log(el);
    } else {
        console.log(el+"!!");
    }
});

It returns:

//Hello
//World
//!!!
over 4 years ago Β· Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
Β© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!