How to Update All Elements in a JavaScript Array
Updating every element in an array is a fundamental data transformation task. You might need to add a value to a list of numbers, convert an array of strings to uppercase, or modify a property on every object in a collection. Modern JavaScript provides powerful, functional methods for this, depending on whether you want to modify the original array or create a new one.
This guide will teach you the modern, immutable approach using Array.prototype.map() and the classic, mutating approach using Array.prototype.forEach().
The Core Problem: Mutating vs. Immutable Operations
Before you update an array, you must decide on your approach:
- Immutable (Recommended): You create a brand new array with the updated values. This is often safer and leads to more predictable code, as it leaves the original array untouched.
- Mutation (In-Place): You change the original array directly. This is efficient but can sometimes lead to unexpected behavior in complex applications if the original array is being used elsewhere.
Method 1 (Recommended & Immutable): Creating a New Array with map()
The Array.prototype.map() method is the standard, idiomatic tool for creating a new array by transforming every element of an existing one.
The logic: the map() method iterates through each element of an array, executes a callback function on it, and returns a new array containing the results of each callback.
The problem: you have an array of numbers and want to create a new array where each number is doubled.
// Problem: How to double each number in this array?
let numbers = [1, 2, 3, 4];
The solution:
let numbers = [1, 2, 3, 4];
let doubledNumbers = numbers.map(num => {
return num * 2;
});
console.log(doubledNumbers); // # Output: [2, 4, 6, 8]
console.log(numbers); // # Output: [1, 2, 3, 4] (The original is unchanged)
This is the recommended best practice for its clarity, safety, and alignment with functional programming principles.
A more concise version with an implicit return:
let numbers = [1, 2, 3, 4];
let doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8]
Method 2 (Mutation): Modifying the Array In-Place with forEach()
If you need to modify the original array directly, the Array.prototype.forEach() method is the right tool. It provides both the element and its index, allowing you to reassign the value at that position.
Problem: you want to convert every string in an array to uppercase, modifying the original array.
// Problem: How to convert each of these strings to uppercase in-place?
let words = ['apple', 'banana', 'cherry'];
Solution:
let words = ['apple', 'banana', 'cherry'];
words.forEach((word, index) => {
// Use the index to reassign the value at the current position.
words[index] = word.toUpperCase();
});
console.log(words); // # Output: ['APPLE', 'BANANA', 'CHERRY'] (The original is now changed)
While this works, the immutable map() approach is generally preferred in modern JavaScript because it leads to more predictable code, especially in larger applications.
A Special Case: Setting All Elements to the Same Value
If your goal is to change all elements in an array to the same static value, the Array.prototype.fill() method is the most efficient tool. It modifies the array in place.
let myArray = [1, 2, 3, 4, 5];
// Fill the entire array with the number 0.
myArray.fill(0);
console.log(myArray); // # Output: [0, 0, 0, 0, 0]
Conclusion
Updating all elements in a JavaScript array is a simple task with clear, modern solutions that depend on your goal of mutation vs. immutability.
- To create a new array with the updated elements (immutable), the recommended best practice is to use
array.map(). - If you must mutate the original array, use
array.forEach()with the index to reassign the value at each position. - To set all elements to the same static value, use the efficient
array.fill()method.