Is it possible to change values of the array when doing foreach() in javascript?


Array is a data type which can store multiple elements of similar data types. For example, array is declared as integer data type then it stores one or more elements of the integer data type.

In arrays the element can be manipulated when they are in a loop by using any of the mathematical operations or so. For example, if the array elements are numbers, then the numbers can be multiplied by a fixed number or can be added or subtracted also. The change in the array elements can be done by using a user defined program and the result of each element depends on the functionality of this function.

The forEach method

The forEach() loop takes the user defined function as on argument. This function has three parameters including the optional parameters. The first parameter is the value of the array which is to be updated while using in the forEach loop.

The second parameter is an optional parameter i.e., the index of the current element and the third parameter is also an optional parameter i.e., the array which is to be made updations while iterating in forEach loop.

Syntax

This is the syntax of the foreach() loop in JavaScript −

Object.forEach(function(value,index,array)

Where,

  • function(value,index,array) − This is the function which is the argument for forEach loop. This is the user defined function which is called for each element.

  • value − This is the current value of the given array or iterative object.

  • index − This is the index of the current value from the given array ot iterative object.

  • array − This is the array on which the changes are made while in a forEach loop.

Example 1

In the following example we are trying to update array elements using forEach() loop −

let employee = ['Abdul', 'Yadav', 'Badavath','Jason']; console.log("The given array with its type is:",employee,typeof(employee)); employee.forEach(myFun); function myFun(item, index, a) { a[index] = 'Intern-Software Engineer ' + item; } console.log("The updated array while in foreach loop with the type is:"); console.log(employee);

Example 2

Following is another example here we are changing the case of the elements of an array (string values) to sentence case −

let employee = ['abdul', 'yadav', 'badavath','jason']; console.log("The given array with its type is:",employee,typeof(employee)); employee.forEach(myFun); function myFun(item, index, a) { a[index] = item[0].toUpperCase() + item.substring(1) } console.log("The updated array while in foreach loop with is:", employee);

Example 3

In this example we are replacing elements of the array with their square values.

let arr = [1, 2, 3, 4]; arr.forEach((val, index) => arr[index] = val * val); console.log(arr);

Updated on: 02-Sep-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements