JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to set all array elements to a specific value in JavaScript?

How to set all array elements to a specific value in JavaScript?

To set all array elements to a specific value, call the fill() method and pass the specific value to it. Suppose you want all array elements to be 100, so you write the JavaScript code like this:

let arr = new Array(5);
arr.fill(100);
console.log(arr); //[100, 100, 100, 100, 100]

The value passed to the fill() method is assigned to each element of an array.

You can also call the fill() method on the existing array.

let arr = [11, 22, 33, 44];
arr.fill(100);
console.log(arr); //[100, 100, 100, 100]

If you don't want to use the fill() method, you can use a for loop to set the elements of an array. On each iteration, assign the value to the element at the current processing index.

let arr = [11, 22, 33, 44];
for(let i=0; i<arr.length; i++){
  arr[i] = 100;
}
console.log(arr);

Recommended Posts