JavaScript Program to Create an Array with a Specific Length and Pre-filled Values
Last Updated :
31 Oct, 2023
In JavaScript, we can create an array with a specific length and pre-filled values using various approaches. This can be useful when we need to initialize an array with default or placeholder values before populating it with actual data.
The Array constructor can be used to create an array of a specific length. The fill() method can fill this array with a specified value.
Syntax:
const filledArray = new Array(length).fill(value);
Example: Below is the implementation of the above approach
Javascript
const length = 5;
const value = 5;
const filledArray = new Array(length).fill(value);
console.log(filledArray);
|
Method 2: Using a Loop to Initialize Values
We can use a loop to iterate through the desired length and assign values.
Syntax:
const filledArray = Array.from();
for (let i = 0; i < length; i++) {
filledArray.push(value);
}
Example: Below is the implementation of the above approach
Javascript
const length = 5;
const filledArray = new Array();
for (let i = 0; i < length; i++) {
filledArray.push(i + 1);
}
console.log(filledArray);
|
Method 3: Using the map() Method
The map() method can be used to create an array by applying a function to each element.
Syntax:
const filledArray = Array.from({ length }).map(() => value);
Example: Below is the implementation of the above approach
Javascript
const length = 5;
const filledArray =
Array.from({ length })
.map(() => 5);
console.log(filledArray);
|
Share your thoughts in the comments
Please Login to comment...