Home » JavaScript Array from() Method

JavaScript Array from() Method

by Online Tutorials Library

JavaScript Array from() Method

The from() method creates a new array that holds the shallow copy from an array or iterable object. When applied to a string, each word gets converted to an array element in the new array.

Syntax

There is a following possible syntax:

Parameter

  1. object: It is the name of the array-like or iterable object on which from() method will be applied.
  2. map_fun: It is an optional parameter used for calling the elements of the array via map() function.
  3. thisArg: An optional parameter whose value is used as ‘this’ when we execute the map_fun.

Return

It returns a newly created array.

Note: Array from() method allows to create a new array from an array-like object, specified with a length property and indexed elements. The length property of the from() method is 1 usually.

JavaScript Array from() Method Example

Let’s see the below examples to understand better:

Example1

Here’s a simple example to create an array from a string.

Test it Now

Output:

JavaScript Array from() Method

In the output displayed, it is clear that each letter of the string gets converted to an array element.

Example2

Here’s an example to create an array from an array-like object.

Test it Now

Output:

JavaScript Array from() Method

Example3

Here’s an example to convert a given Set into an array.

Test it Now

Output:

JavaScript Array from() Method

In the output, we can see that each value occurred only once.

Note: A set is a collection of values that occur only once in the resultant/output. Such behavior maintains the uniqueness of each value present in the set.

Example1

Here’s an example of generating a sequence of numbers using length property.

Test it Now

Output:

JavaScript Array from() Method


Next TopicJavaScript Array

You may also like