How to mutate original array in Javascript?
We can mutate the original array in JavaScript in multiple ways. The straightforward way is to use forEach loop. Let’s consider the following example to mutate array in Javascript using forEach.
Using forEach
const carBrand = ['BMW', 'Audi', 'Toyota', 'Tesla', 'TATA']; carBrand.forEach((item, index, originalArr) => originalArr[index] = item.concat(' Inc')); console.log(carBrand);
Using map
const carBrand = ['BMW', 'Audi', 'Toyota', 'Tesla', 'TATA']; carBrand.map((item, index) => carBrand[index] = item.concat(' Inc')); console.log(carBrand);
One downside of using .map is it creates a new array with the modified value.
const newArr = carBrand.map((item, index) => item.concat(' Inc')); console.log(newArr);