How to Auto Fill Array with Default Values in JavaScript

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

Related Articles:

Method 1: 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"]

Method 2: 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"]

Method 3: 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"]