JavaScript – Auto Fill Array with Default Values

In JavaScript, there are many ways to Auto Fill Array with Default Values. In this tutorial, we will cover simple loop, Array.from() & Array.fill() method.

Methods to Auto Fill Array

  • Using Simple Loop
  • Using Array.from() method
  • Using Array.fill() method

Using Simple Loop

const length = 5;
const filledArray = [];
for(let i = 0; i < length; i++) {
  filledArray.push('CodeyMaze');
}
console.log(filledArray);

The Output of the above code will be

["CodeyMaze", "CodeyMaze", "CodeyMaze", "CodeyMaze", "CodeyMaze"]

Using Array.from() method

const length = 5;
const filledArray = Array.from({length}, (_, index) => 'CodeyMaze');
console.log(filledArray);

The Output of the above code will be

["CodeyMaze", "CodeyMaze", "CodeyMaze", "CodeyMaze", "CodeyMaze"]

Using Array.fill() method

const length = 5;
const fillValue = 'JavaScript';
const filledArray = new Array(length).fill(fillValue);
console.log(filledArray);

The Output of the above code will be

["JavaScript", "JavaScript", "JavaScript", "JavaScript", "JavaScript"]

Similar Reads