🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › forEach
Array.prototype.forEach() - JavaScript | MDN
The following example illustrates an alternative approach, using forEach(). The following code logs a line for each element in an array: js · const logArrayElements = (element, index /*, array */) => { console.log(`a[${index}] = ${element}`); }; // Notice that index 2 is skipped, since there is no item at // that position in the array.
🌐
W3Schools
w3schools.com › jsref › jsref_foreach.asp
W3Schools.com
JS Arrays · Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean ·
🌐
Stack Overflow
stackoverflow.com › questions › 61900775 › using-index-in-foreach-array
Using Index in forEach Array
Please add some jsfiddle example us, you'll get help easier, if we can see a working example. ... Instead of messing with index etc.. you can attach the event handler to the tr and just reference e.target in the event handler. I also cleaned up your adding of tr. const myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}] myArray.forEach((item, index) => { let row = document.createElement("tr"); let cell = document.createElement("td"); cell.innerHTML = item.number; row.appendChild(cell); cell = document.createElement("td"); cell.innerHTML = item.otherNumber; row.appendChild(cell); document.getElementById('myElementID').appendChild(row); row.addEventListener('dblclick', (e) => { console.log(e.target); }); });
🌐
Mimo
mimo.org › glossary › javascript › foreach
JavaScript forEach(): Syntax, Usage, and Examples
JSX · Open in Mimo · Open in Mimo · Copy Code · const scores = [92, 85, 74]; scores.forEach((score, index) => { console.log(`Score #${index + 1}: ${score}`); }); This makes code shorter and easier to read. forEach provides a functional programming pattern.
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › foreach-index
Get The Current Array Index in JavaScript forEach() - Mastering JS
// Prints "0: a, 1: b, 2: c" ['a', 'b', 'c'].forEach(function callback(value, index) { console.log(`${index}: ${value}`); });
🌐
Learnjavascript
blog.learnjavascript.online › posts › javascript-foreach-index
JavaScript forEach index - Learn JavaScript Blog
March 4, 2020 - When looping through an array in JavaScript, it may be useful sometimes to get the index of every item in the array. This is possible with .forEach method, let's take an example to illustrate it:
Find elsewhere
🌐
Chart.js
chartjs.org › docs › latest › samples › other-charts › combo-bar-line.html
Combo bar/line | Chart.js
const actions = [ { name: 'Randomize', ... data.datasets[index].data.push(Utils.rand(-100, 100)); } chart.update(); } } }, { name: 'Remove Dataset', handler(chart) { chart.data.datasets.pop(); chart.update(); } }, { name: 'Remove Data', handler(chart) { chart.data.labels.splice(-1, 1); // remove the label first chart.data.datasets.forEach(dataset => ...
🌐
Tabnine
tabnine.com › home › how to use the array foreach() method in javascript
How to Use The Array forEach() Method in JavaScript - Tabnine
September 17, 2024 - index is the index of the current item in the array being processed · ○ arr is the array being looped through. Since forEach() returns undefined, this can be useful if changes to the original array are required (the example below shows ...
🌐
Tskr
tskr.io › l7y
AntiBot Cloud: скрипт для защиты сайтов на php от плохих ботов.
February 24, 2026 - This process is automatic. Your browser will redirect to your requested content shortly · Please allow up to 1 seconds
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript | MDN
Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). const array = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array.reduce( (accumulator, currentValue) => accumulator + currentValue, initialValue, ); console.log(sumWithInitial); // Expected output: 10 · js ·
🌐
freeCodeCamp
freecodecamp.org › news › javascript-foreach-js-array-for-each-example
JavaScript forEach() – JS Array For Each Loop Example
November 7, 2024 - index: index is an optional argument that carries the index of the currentElement. array: The array is an optional argument that returns the array that was passed to the forEach() method.
Top answer
1 of 12
1229

for…in iterates over property names, not values (and did so in an unspecified order up until ES2020*). You shouldn’t use it to iterate over arrays. For them, there’s ES6’s Array.prototype.entries, which now has support across current browser versions:

const myArray = [123, 15, 187, 32];

for (const [i, value] of myArray.entries()) {
  console.log(`${i}: ${value}`);
}

// 0: 123
// 1: 15
// 2: 187
// 3: 32
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }

Or, for extended compatibility with older browsers, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

myArray.forEach(function (value, i) {
  console.log('%d: %s', i, value);
});

For iterables in general (where you would use a for…of loop rather than a for…in), iterator helpers are now in the language. You can use Iterator.prototype.forEach to iterate over an entire iterable with an index:

function* fibonacci() {
  let a = 0;
  let b = 1;

  for (;;) {
    yield a;
    [a, b] = [b, a + b];
  }
}

fibonacci().take(10).forEach((x, i) => {
  console.log(`F_${i} = ${x}`);
});
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }

More generally, Iterator#map can associate the values yielded by an iterator with their indexes:

fibonacci().map((x, i) => [i, x])

Not every iterable (or iterator!) is an Iterator, but you can convert every iterable to an Iterator with Iterator.from.

Without support for iterator helpers, you can use a generator function instead:

function* enumerate(iterable) {
  let i = 0;

  for (const x of iterable) {
    yield [i, x];
    i++;
  }
}

for (const [i, obj] of enumerate(myArray)) {
  console.log(i, obj);
}

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.

* The order is still unspecified under certain circumstances, including for typed arrays, proxies, and other exotic objects, as well as when properties are added or removed during iteration.

2 of 12
494

In ES6, it is good to use a for... of loop. You can get index in for... of like this

for (let [index, val] of array.entries()) {
  // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

🌐
Medium
medium.com › @francois.barrailla › javascript-iterate-over-array-values-and-indexes-using-a-for-of-loop-106a58972b24
JavaScript: Iterate over array values and indexes using a for-of loop | by François Barrailla | Medium
July 8, 2020 - for (const [index, name] of names.entries()) { console.log(`Hello ${name}, your index is ${index}!`); } We also could use the Array.prototype.forEach method to perform the iteration over the values and indexes.