Open In App

JavaScript Array from() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript Array.from() method is used to create a new array instance from a given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance, and in the case of integer values, a new array instance simply takes the elements of the given array.

 Syntax:

Array.from(object, mapFunction, thisValue);

Parameters:

  • object: This parameter holds that object that will convert into an array
  • mapFunction: This parameter is optional and used to call on each item of the array.
  • thisValue: This parameter is optional, it holds the context to be passed as this is to be used while executing the mapFunction. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.

Return value:

It returns a new Array instance whose elements are the same as the given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance.

Example 1: In this example, we will see the basic use of the Array from() method.

JavaScript




console.log(Array.from("This is JavaScript Array " +"from() Method"));


Output

[
  'T', 'h', 'i', 's', ' ', 'i', 's',
  ' ', 'J', 'a', 'v', 'a', 'S', 'c',
  'r', 'i', 'p', 't', ' ', 'A', 'r',
  'r', 'a', 'y', ' ', 'f', 'r', 'o',
  'm', '(', ')', ' ', 'M', 'e', 't',
  'h', 'o', '...

Example 2: Here we see that output creates a new array whose content is the same as input in the case of an integer.

JavaScript




console.log(Array.from("GeeksforGeeks"));
console.log(Array.from([10, 20, 30]));


Output

[
  'G', 'e', 'e', 'k',
  's', 'f', 'o', 'r',
  'G', 'e', 'e', 'k',
  's'
]
[ 10, 20, 30 ]

Example 3: Here as we see that output creates a new array whose content is the same as input every alphabet of the string is converted to an element of the new array instance.

JavaScript




// Here input array is [1,2,3] and output
// become double of each elements.
console.log(Array.from([1, 2, 3],
            x => x + x));


Output

[ 2, 4, 6 ]

Note: If we take a complex number as the parameter, it returns an error because only array and string can be taken as the parameter. 

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

  • Google Chrome 45.0
  • Microsoft Edge 12.0
  • Mozilla Firefox 32.0
  • Safari 9.0
  • Opera 25.0

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Last Updated : 03 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads