foreach in javascript

To loop through an array in JavaScript, you can use the forEach() method. The forEach() method executes a provided function once for each array element.

Here's an example of how to use forEach():

index.tsx
var array = ['Apple', 'Banana', 'Orange'];

array.forEach(function(element) {
  console.log(element);
});
106 chars
6 lines

This will output:

index.tsx
Apple
Banana
Orange
20 chars
4 lines

In the callback function, element represents the current element being processed in the loop. You can also include two additional parameters: index, which represents the index of the current element being processed, and array, which is the array that forEach() is being applied to.

index.tsx
var array = ['Apple', 'Banana', 'Orange'];

array.forEach(function(element, index, array) {
  console.log(element, index);
});
127 chars
6 lines

This will output:

index.tsx
Apple 0
Banana 1
Orange 2
26 chars
4 lines

Note that the forEach() method is not supported in Internet Explorer 8 or earlier versions, so you may need to use a different method or a polyfill if you need to support older browsers.

gistlibby LogSnag