How to use the map() Method In Javascript
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
const length = 5;
const filledArray =
Array.from({ length })
.map(() => 5);
console.log(filledArray);
Output
[ 5, 5, 5, 5, 5 ]
JavaScript Program to Create an Array with a Specific Length and Pre-filled Values
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.
Table of Content
- Using the Array() Constructor and fill() Method
- Using a Loop to Initialize Values
- Using the map() Method
- Using Array.from with a Mapping Function