create a foreach loop in javascript

In JavaScript, the forEach() method is used to execute a provided function once for each array or array-like element. Here is an example of how to use a forEach() loop:

index.tsx
const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => {
  console.log(number);
});
89 chars
6 lines

In this example, the forEach() method is called on the numbers array, and a function is passed as an argument. The function takes each element of the array as its argument, and that element is logged to the console.

You can also use a traditional for loop to achieve the same effect. Here's an example:

index.tsx
const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
106 chars
6 lines

This loops over each element in the array, logging it to the console. However, it requires a bit more setup than using forEach().

related categories

gistlibby LogSnag