each in javascript

In Javascript, the forEach() method is used to iterate over an array and execute a function for each element. Here is an example:

index.tsx
let myArray = [1, 2, 3, 4, 5];
myArray.forEach(function(element) {
  console.log(element);
});
95 chars
5 lines

Output:

index.tsx
1
2
3
4
5
10 chars
6 lines

In this example, we first declare an array myArray with 5 elements. We then call the forEach() method on the array and pass in a function that takes an argument element. The function simply logs the value of element to the console. The forEach() method will then execute this function for each element in the array.

You can also use an arrow function to make the code more concise:

index.tsx
let myArray = [1, 2, 3, 4, 5];
myArray.forEach(element => console.log(element));
81 chars
3 lines

Output:

index.tsx
1
2
3
4
5
10 chars
6 lines

gistlibby LogSnag