Set all Array Elements to a Specific Value in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Robert Metz

Set all Array Elements to a Specific Value #

Use the fill() method to set the elements on an array to a specific value, e.g. new Array(3).fill('example') creates an array of 3 elements with the value example. The fill method changes the elements in an array setting them to a static value and returns the modified array.

index.js
// โœ… Using fill() const arr1 = new Array(3).fill('value'); // ๐Ÿ‘‡๏ธ ['value', 'value', 'value'] console.log(arr1); // โœ… Can take length from existing array const existingArr = [1, 2, 3]; const newArr = new Array(existingArr.length).fill(100); // ๐Ÿ‘‡๏ธ [100, 100, 100] console.log(newArr);

We called the Array.fill method on an existing array with a set length to fill the array with a specific value.

The parameter we passed to the fill method is the value with which to fill the array.

The Array() constructor creates an array of N empty elements, which we can fill using the fill() method.

index.js
// ๐Ÿ‘‡๏ธ [,,] console.log(new Array(3))

If the value is determined based on a value in an existing array, use the Array.map method instead.

Set all Array Elements to a Specific Value using map() #

To set the elements of an array to a specific value, use the map() method to iterate over the array and return the value on each iteration. The map method returns a new array that contains all the values returned from the provided function.

index.js
const arr2 = [1, 2, 3]; const arr3 = arr2.map(element => `_${element}_`); // ๐Ÿ‘‡๏ธ ['_1_', '_2_', '_3_'] console.log(arr3);

The function we passed to the map() method gets called with each element in the array.

You can use the value of the element to get the new value that the array should contain.

Whatever we return from the function gets added to the array that the map() method returns.

The map method creates a new array, it doesn't change the original array.

If you prefer to mutate the original array in place, use a basic for loop instead.

Set all Array Elements to a Specific Value using for loop #

To set the elements of an array to a specific value, use a for loop to iterate over the array and on each iteration, set the element at the current index to the specific value.

index.js
const arr4 = [1, 2, 3]; for (let i = 0; i < arr4.length; i++) { arr4[i] = arr4[i] + 100; } // ๐Ÿ‘‡๏ธ [101, 102, 103] console.log(arr4);

This approach mutates the original array, instead of returning a new array.

We use the index to access the current array element and increment its value by 100.

This is a more manual approach that the previous two, but is a good option if you want to change the array and not create a new one.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee