How to use apply() and map() Methods In Javascript

We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined.

Example 1: In this example, we are using the apply() and map() method for creating an array.

Javascript
let arr = Array.apply(null, Array(5))
    .map(function () { });

console.log(arr.length);
console.log(arr);

Output:

5
[undefined, undefined, undefined, undefined, undefined]

Example 2: We will put the values of the indexes so it will give you an array of length 5 and its values will be the index number 0, 1, 2, 3, 4.

Javascript
let arr = Array.apply(null, Array(5))
    .map(function (y, i) { return i; });

console.log(arr.length);
console.log(arr)

Output:

5
[0, 1, 2, 3, 4]

Create an array of given size in JavaScript

Creating an array of a specific size can be achieved through various methods, each suited to different situations. In this article, we will explore several approaches to creating arrays of a desired size, accompanied by examples for each method.

Below are the following ways:

Table of Content

  • Using JavaScript array() constructor
  • Using apply() and map() Methods
  • Using JavaScript Array.from() Method
  • Using for loop
  • Using the spread syntax with Array.fill()

Similar Reads

Method 1: Using JavaScript array() constructor

In this method, we use the JavaScript array() constructor to create an array. It will just create an array without any value with a given size. However, the values of the array will be undefined....

Method 2: Using apply() and map() Methods

We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined....

Method 3: Using JavaScript Array.from() Method

In ES6, we got something new called JavaScript Array.from() function, by which we can create an array of a given size....

Method 4: Using for loop

Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false....

Method 5: Using the spread syntax with Array.fill()

Using the spread syntax `[…Array(size)]`, where size is the desired array length, creates an array of that size. Combining it with `.fill(0)` fills the array with the specified value (`0` in this case), resulting in an array of the desired size filled with the specified value....