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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order