Skip to main content

Foreach Javascript

JavaScript provides a variety of methods for iterating over arrays. These methods can be used to loop through the elements of an array and perform some action on each element.

In this tutorial, you'll learn about the different methods for iterating over arrays in JavaScript.

Let's explore these methods in more detail. 💫

JavaScript Array forEach()​

The forEach() method is used to iterate over an array and execute a provided function once for each element in the array. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using forEach():

array.forEach(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which forEach() was called.
const fruits = ["apple", "banana", "orange", "grape"];

fruits.forEach((fruit) => {
console.log(fruit);
});

As an example:

Editor

Loading...

In the example above:

  • The forEach() method is called on the fruits array.
  • The arrow function passed as an argument to forEach() takes a single argument fruit which represents the current element being processed in the array.
  • The function simply prints the value of fruit to the console for each element in the array.

JavaScript Array map()​

The map() method is used to create a new array with the results of calling a provided function on every element in the calling array. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using map():

array.map(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which map() was called. Here's an example that demonstrates the use of map() to create a new array with the length of each element in an array:
const words = ["apple", "banana", "orange", "grape"];

const wordLengths = words.map((word) => {
return word.length;
});

console.log(wordLengths); // [5, 6, 6, 5]

As an example:

Editor

Loading...

In the above example:

  • HTML code creates an unordered list (<ul>)
  • Uses map() method to create a new array called doubledNumbers
  • doubledNumbers contains each number in the numbers array multiplied by 2
  • Loops through the doubledNumbers array using forEach() method
  • For each doubled number, creates a new <li> element with the doubled number as its text content
  • Appends the <li> element to the <ul> element using the appendChild() method

JavaScript Array flatMap()​

The flatMap() method is similar to the map() method, but it first maps each element using a mapping function, then flattens the result into a new array. It is available in ECMAScript 2019 (ES10) and later versions of JavaScript.

Here's the syntax for using flatMap():

array.flatMap(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which flatMap() was called. Here's an example that demonstrates the use of flatMap() to flatten a nested array:
const numbers = [1, 2, 3, 4];

const flattenedNumbers = numbers.flatMap((number) => {
return [number, number * 2];
});

console.log(flattenedNumbers); // [1, 2, 2, 4, 3, 6, 4, 8]

As an example:

Editor

Loading...

In the above example:

  • flatMap() method takes a callback function that returns an array.
  • The resulting array is flattened into a single level.
  • The callback function returns an array with the original number and the number multiplied by 2.
  • The flatMap() method flattens the resulting array into a single level.
  • Loops through the flattenedNumbers array using forEach() method.
  • For each flattened number, creates a new <li> element with the flattened number as its text content.
  • Appends the <li> element to the <ul> element using the appendChild() method.

JavaScript Array filter()​

The filter() method is used to create a new array with all elements that pass the test implemented by a provided function. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using filter():

array.filter(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which filter() was called. Here's an example that demonstrates the use of filter() to create a new array of even numbers:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6, 8]

As an example:

Editor

Loading...

In the above example:

  • filter() method takes a callback function that returns a boolean value based on a condition
  • If the condition is true, the current element will be included in the new array, otherwise it will be excluded
  • The callback function checks if the current number is even using the modulo operator %
  • The callback function only returns true for even numbers
  • Loops through the evenNumbers array using forEach() method
  • For each even number, creates a new <li> element with the even number as its text content
  • Appends the <li> element to the <ul> element using the appendChild() method

JavaScript Array reduce()​

The reduce() method is used to iterate over an array and accumulate a single value based on the values in the array. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using reduce():

array.reduce(callbackFunction, initialValue);

The callbackFunction takes two arguments:

  • accumulator (required): The accumulated value returned by the previous iteration of the callback function.
  • currentValue (required): The value of the current element being processed in the array.

The initialValue parameter is optional and specifies the initial value of the accumulator. If it is not provided, the first element of the array is used as the initial value.

Here's an example that demonstrates the use of reduce() to calculate the sum of all values in an array:

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

const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);

console.log(sum); // 15

As an example:

Editor

Loading...

In the above example:

  • reduce() method takes a callback function and an initial value for the accumulator
  • The callback function takes two arguments: the accumulator and the current value of the array being processed
  • The accumulator starts with the initial value
  • The callback function returns a new value for the accumulator, which is used in the next iteration of the loop
  • The callback function adds the current value to the accumulator on each iteration
  • Calculates the sum using reduce().

JavaScript Array reduceRight()​

The reduceRight() method is similar to the reduce() method, but it reduces the array from right-to-left instead of left-to-right. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using reduceRight():

array.reduceRight(callbackFunction, initialValue);

The callbackFunction takes two arguments:

  • accumulator (required): The accumulated value returned by the previous iteration of the callback function.
  • currentValue (required): The value of the current element being processed in the array. The initialValue parameter is optional and specifies the initial value of the accumulator. If it is not provided, the last element of the array is used as the initial value.

Here's an example that demonstrates the use of reduceRight() to concatenate a string from an array of words:

const words = ["hello", "world", "this", "is", "a", "test"];

const concatenatedString = words.reduceRight((accumulator, currentValue) => {
return `${accumulator} ${currentValue}`;
});

console.log(concatenatedString); // "test a is this world hello"

As an example:

Editor

Loading...
  • reduceRight() method is similar to reduce() method, but starts at the end of the array and works backwards.
  • The callback function takes two arguments: the accumulator and the current value of the array being processed.
  • The accumulator starts with the last value of the array.
  • The callback function returns a new value for the accumulator, which is used in the next iteration of the loop.
  • The callback function concatenates the current value to the accumulator with a space between them. Concatenates the strings using reduceRight().

JavaScript Array every()​

The every() method is used to check if all elements in an array pass a certain condition specified by a provided function. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using every():

array.every(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which every() was called. The every() method returns a boolean value. It returns true if the callback function returns a truthy value for all elements in the array, otherwise it returns false.

Here's an example that demonstrates the use of every() to check if all elements in an array are even:

const numbers = [2, 4, 6, 8, 10];

const allEven = numbers.every((number) => {
return number % 2 === 0;
});

console.log(allEven); // true

As an example:

Editor

Loading...

In the above example:

  • every() method is used to check if all elements in the numbers array are even.
  • The every() method returns true if the callback function returns true for every element in the array, and false otherwise.
  • The callback function takes one argument, the current value of the array being processed.
  • The callback function returns true if the number is even and false otherwise.
  • Checks if all elements are even using every().

JavaScript Array some()​

The some() method is used to check if at least one element in an array passes a certain condition specified by a provided function. It takes a callback function as an argument, which is executed for each element in the array.

Here's the syntax for using some():

array.some(callbackFunction);

The callbackFunction takes three arguments:

  • currentValue (required): The value of the current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which some() was called. The some() method returns a boolean value. It returns true if the callback function returns a truthy value for at least one element in the array, otherwise it returns false.

Here's an example that demonstrates the use of some() to check if at least one element in an array is odd:

const numbers = [2, 4, 6, 8, 9];

const hasOdd = numbers.some((number) => {
return number % 2 !== 0;
});

console.log(hasOdd); // true

As an example:

Editor

Loading...

In the above example:

  • The some() method is used to check if the numbers array has at least one odd number.
  • The some() method returns true if the callback function returns true for at least one element in the array, and false otherwise.
  • The callback function takes one argument, the current value of the array being processed.
  • The callback function returns true if the number is odd and false otherwise.

JavaScript Array indexOf()​

The indexOf() method is used to find the index of the first occurrence of a specified element in an array. It returns the index of the first occurrence of the specified element, or -1 if the element is not found.

Here's the syntax for using indexOf():

array.indexOf(searchElement, fromIndex);

The searchElement parameter is required and specifies the element to search for in the array.

The fromIndex parameter is optional and specifies the starting index for the search. If it is not provided, the search starts at index 0. If fromIndex is greater than or equal to the length of the array, indexOf() returns -1.

Here's an example that demonstrates the use of indexOf() to find the index of a specific element in an array:

const fruits = ["apple", "banana", "cherry", "apple", "banana"];

const index = fruits.indexOf("apple");

console.log(index); // 0

In the example above:,

  • The indexOf() method is called on the fruits array with the argument "apple".
  • The method returns the index of the first occurrence of "apple", which is 0.

If the specified element is not found in the array, indexOf() returns -1. For example:

const fruits = ["apple", "banana", "cherry"];

const index = fruits.indexOf("orange");

console.log(index); // -1

In the example above:,

  • The indexOf() method is called on the fruits array with the argument "orange".
  • Since "orange" is not found in the array, indexOf() returns -1.

JavaScript Array lastIndexOf()​

The lastIndexOf() method is similar to the indexOf() method, but it returns the index of the last occurrence of a specified element in an array, instead of the first occurrence. It returns the index of the last occurrence of the specified element, or -1 if the element is not found.

Here's the syntax for using lastIndexOf():

array.lastIndexOf(searchElement, fromIndex);
  • The searchElement parameter is required and specifies the element to search for in the array.
  • The fromIndex parameter is optional and specifies the starting index for the search from the end of the array.
  • If it is not provided, the search starts at the last index of the array.
  • If fromIndex is greater than or equal to the length of the array, lastIndexOf() returns -1.

Here's an example that demonstrates the use of lastIndexOf() to find the index of the last occurrence of a specific element in an array:

const fruits = ["apple", "banana", "cherry", "apple", "banana"];

const index = fruits.lastIndexOf("apple");

console.log(index); // 3

In the example above:,

  • The lastIndexOf() method is called on the fruits array with the argument "apple".
  • The method returns the index of the last occurrence of "apple", which is 3.

If the specified element is not found in the array, lastIndexOf() returns -1. For example:

const fruits = ["apple", "banana", "cherry"];

const index = fruits.lastIndexOf("orange");

console.log(index); // -1

In the example above:

  • The lastIndexOf() method is called on the fruits array with the argument "orange".
  • Since "orange" is not found in the array, lastIndexOf() returns -1.

JavaScript Array find()​

The find() method is used to retrieve the first element in an array that satisfies a specified condition. It returns the value of the first element in the array that satisfies the provided testing function, or undefined if no element satisfies the condition.

Here's the syntax for using find():

array.find(callback(element[, index[, array]])[, thisArg])

The callback function is required and is called once for each element in the array. It takes three arguments:

  • element: The current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which the find() method was called.

The thisArg parameter is optional and specifies the value to be used as this when executing the callback function.

Here's an example that demonstrates the use of find() to retrieve the first even number in an array:

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

const evenNumber = numbers.find(function (number) {
return number % 2 === 0;
});

console.log(evenNumber); // 2

In the example above:

  • The find() method is called on the numbers array with a callback function that checks if a number is even.
  • The method returns the first even number in the array, which is 2.

If no element satisfies the condition, find() returns undefined. For example:

const numbers = [1, 3, 5, 7];

const evenNumber = numbers.find(function (number) {
return number % 2 === 0;
});

console.log(evenNumber); // undefined

In the example above:

  • The find() method is called on the numbers array with a callback function that checks if a number is even.
  • Since there are no even numbers in the array, find() returns undefined.

JavaScript Array findIndex()​

The findIndex() method is similar to the find() method, but it returns the index of the first element in an array that satisfies a specified condition, instead of the element itself. It returns the index of the first element that satisfies the provided testing function, or -1 if no element satisfies the condition.

Here's the syntax for using findIndex():

array.findIndex(callback(element[, index[, array]])[, thisArg])

The callback function is required and is called once for each element in the array. It takes three arguments:

  • element: The current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array on which the findIndex() method was called.

The thisArg parameter is optional and specifies the value to be used as this when executing the callback function.

Here's an example that demonstrates the use of findIndex() to retrieve the index of the first even number in an array:

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

const evenIndex = numbers.findIndex(function (number) {
return number % 2 === 0;
});

console.log(evenIndex); // 1

In the example above:

  • The findIndex() method is called on the numbers array with a callback function that checks if a number is even.
  • The method returns the index of the first even number in the array, which is 1.

If no element satisfies the condition, findIndex() returns -1. For example:

const numbers = [1, 3, 5, 7];

const evenIndex = numbers.findIndex(function (number) {
return number % 2 === 0;
});

console.log(evenIndex); // -1

In the example above:

  • The findIndex() method is called on the numbers array with a callback function that checks if a number is even.
  • Since there are no even numbers in the array, findIndex() returns -1.

JavaScript Array.from()​

The Array.from() method is used to create a new array from an iterable or array-like object, such as a string, set, or map. It returns a new array with elements created from the iterable or array-like object.

Here's the syntax for using Array.from():

Array.from(iterable[, mapFn[, thisArg]])

The iterable parameter is required and specifies the iterable or array-like object to convert to an array.

The mapFn parameter is optional and specifies a function to be called on each element in the array. This function can be used to map the elements to a new value or perform some other operation on them. The function takes two arguments:

  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.

The thisArg parameter is optional and specifies the value to be used as this when executing the mapFn function.

Here's an example that demonstrates the use of Array.from() to create an array from a string:

const str = "hello";
const arr = Array.from(str);

console.log(arr); // ['h', 'e', 'l', 'l', 'o']

In the example above:

  • The Array.from() method is called with the str string as the iterable parameter.
  • The method returns a new array with elements created from the characters in the string.

Here's an example that demonstrates the use of Array.from() to create an array of square numbers:

const arr = [1, 2, 3, 4, 5];
const squareArr = Array.from(arr, function (num) {
return num * num;
});

console.log(squareArr); // [1, 4, 9, 16, 25]

In the example above:

  • The Array.from() method is called with the arr array as the iterable parameter and a callback function that squares each element in the array.
  • The method returns a new array with elements created from the squared values of the original array.

JavaScript Array Keys()​

The keys() method is a built-in JavaScript array method that returns a new array iterator object that contains the keys (indexes) of each element in the array. The keys are returned in the form of an array with each element being the index of the corresponding element in the array.

Here's the syntax for using keys():

array.keys();

The keys() method takes no arguments.

Here's an example that demonstrates the use of keys():

const arr = ["apple", "banana", "orange"];
const iterator = arr.keys();

for (const key of iterator) {
console.log(key); // 0, 1, 2
}

In the example above:

  • The keys() method is called on the arr array to create an iterator object that contains the keys of the array.
  • The for...of loop is then used to iterate over the iterator and log each key to the console.
info

The keys() method can be useful when you need to loop over the indexes of an array, but not the values.

JavaScript Array entries()​

The entries() method is a built-in JavaScript array method that returns a new array iterator object that contains key-value pairs for each element in the array. Each key-value pair is represented as a two-element array, where the first element is the index (key) of the element in the array and the second element is the value.

Here's the syntax for using entries():

array.entries();

The entries() method takes no arguments.

Here's an example that demonstrates the use of entries():

const arr = ["apple", "banana", "orange"];
const iterator = arr.entries();

for (const [key, value] of iterator) {
console.log(key, value); // 0 'apple', 1 'banana', 2 'orange'
}

In the example above:

  • The entries() method is called on the arr array to create an iterator object that contains key-value pairs for each element in the array.
  • The for...of loop is then used to iterate over the iterator and log each key-value pair to the console.
info

The entries() method can be useful when you need to loop over both the indexes and values of an array.

JavaScript Array includes()​

The includes() method is a built-in JavaScript array method that checks whether an array includes a specific element or not. It returns true if the element is found in the array, and false otherwise.

Here's the syntax for using includes():

array.includes(element, start);

The element argument is the value to search for in the array. The start argument is optional and specifies the index at which to start the search.

Here's an example that demonstrates the use of includes():

const arr = ["apple", "banana", "orange"];
console.log(arr.includes("apple")); // true
console.log(arr.includes("grape")); // false
console.log(arr.includes("banana", 1)); // false
console.log(arr.includes("banana", 0)); // true

In the example above:

  • The includes() method is called on the arr array to check if it includes the values apple, grape, and banana at different starting positions.
  • The method returns true when the value apple is searched for, false when the value grape is searched for (since it is not present in the array), and true when the value banana is searched for starting from index 0, but false when starting from index 1.

The includes() method can be useful when you need to check whether a specific element is present in an array or not, without having to loop through the entire array manually.

JavaScript Array Spread (...)​

The spread syntax ... is a built-in JavaScript syntax that can be used with arrays to expand an array into individual elements. It can be used to create a new array, combine arrays, or pass an array as function arguments.

Here are some examples of how to use the spread syntax with arrays:

Creating a new array with spread syntax:

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]

In the example above:

  • The ...arr1 syntax expands the arr1 array into individual elements, which are then added to the new arr2 array using the spread syntax.

Combining arrays with spread syntax:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]

In the example above:

  • The spread syntax is used to combine the elements of arr1 and arr2 into a new arr3 array.

Passing an array as function arguments with spread syntax:

const arr = [1, 2, 3];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...arr)); // 6

In the example above:

  • The ...arr syntax expands the arr array into individual arguments that are then passed to the sum() function.

The spread syntax can be very useful when working with arrays as it provides a concise and easy way to work with array elements.