#JavaScript April 05, 2023

Notes on JS Array Loops

There are several ways to loop through an array in JavaScript:

for loop: The most common and traditional way of looping through an array is using a for loop, which iterates over the array from the first element to the last element.
Example:
const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

for...of loop: A simpler way of iterating over an array is using the for...of loop, which is designed to loop through iterable objects like arrays.
Example:
const arr = [1, 2, 3, 4, 5];

for (let item of arr) {
  console.log(item);
}

forEach() method: The forEach() method is a built-in method of an array that executes a provided function once for each array element.
Example:
const arr = [1, 2, 3, 4, 5];

arr.forEach(function(item) {
  console.log(item);
});

const arr = [1, 2, 3, 4, 5];

arr.forEach(item => console.log(item));

map() method: The map() method creates a new array with the results of calling a provided function on every element in the original array.
Example:
const arr = [1, 2, 3, 4, 5];

const newArr = arr.map(function(item) {
  return item * 2;
});

console.log(newArr);

filter() method: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Example:
const arr = [1, 2, 3, 4, 5];

const filteredArr = arr.filter(function(item) {
  return item % 2 === 0;
});

console.log(filteredArr);

reduce() method: The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value.
Example:
const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce(function(acc, item) {
  return acc + item;
}, 0);

console.log(sum);

SEARCH