How to use Array.from() Method In Javascript

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

Example: In this example, we are using Array.from() method for creating an array.

Javascript
let arr = Array.from(Array(5));
console.log(arr.length);
console.log(arr);

Output:

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

Example 2: In this example, we will pass the elements as arguments, each character will be an array element

Javascript
let arr = Array.from('w3wiki');
console.log(arr.length);
console.log(arr)

Output:

13
["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"]

Example 3: In this example, we will pass a single element as a parameter and repeat the length we want in our array.

Javascript
let arr = Array.from('G'.repeat(5));
console.log(arr.length);
console.log(arr);

Output:

5
["G", "G", "G", "G", "G"]

Example 4: In this method, we will use two features of ES6, one JavaScript Array.from() function and the arrow function to create an array with a given size.

Javascript
let arr = Array.from({ length: 5 }, (x, i) => 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....