How to use Array.prototype.forEach In Javascript

Using Array.prototype.forEach, you can replace an item in an array by iterating over each element. Check if the current index matches the target index, and if so, update the value at that index. This method directly modifies the original array.

Example:

JavaScript
let arr = [1, 2, 3, 4, 5];
let index = 2; // Index of the item to replace
let newValue = 10;

arr.forEach((item, i, array) => {
  if (i === index) {
    array[i] = newValue;
  }
});

console.log(arr); // [1, 2, 10, 4, 5]

Output
[ 1, 2, 10, 4, 5 ]


How to replace an item from an array in JavaScript ?

Replacing an item from an array in JavaScript refers to the process of updating the value of an existing element at a specified index within the array with a new value, effectively modifying the array content.

Similar Reads

Examples of replacing an item from an array in JavaScript

Table of Content Using Array IndexingUsing the splice() MethodUsing array map() and filter() MethodsUsing the indexOf() MethodUsing Array.prototype.forEach...

Using Array Indexing

In this method, we will use the array indexing and assignment operator to replace an item from an array....

Using the splice() Method

The array type in JavaScript provides us with the splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index....

Using array map() and filter() Methods

Using map() to transform array elements and filter() to selectively include elements based on a condition, creating a new array with modified or filtered values....

Using the indexOf() Method

Using the indexOf() method finds the index of an element in an array, allowing you to perform operations based on its presence or absence....

Using Array.prototype.forEach

Using Array.prototype.forEach, you can replace an item in an array by iterating over each element. Check if the current index matches the target index, and if so, update the value at that index. This method directly modifies the original array....