Javatpoint Logo
Javatpoint Logo

JavaScript Array of() Method

The of() method creates and returns a new array from different a number of arguments. It does not focus on the type and number of arguments. Similar to Array, it also provides a constructor that handles the integer arguments, but in a different manner.

Syntax

The syntax of Array of() method is as follows:

Parameter

It takes and put elements in an array form. Thus, these elements create the array.

Return

It returns a newly created array instance.

JavaScript Array of() Method Example

Let's implement some examples to understand better:

Example1

Here's an example that shows the working of Array of() method.

Test it Now

Output:

The output represents the elements in the array form.

JavaScript Array of() Method

Example2

Here's an example to represent a single value in the form of an array.

Test it Now

Output:

JavaScript Array of() Method

Here, 1 is a single element of the newly created array.

Example3

Test it Now

Output:

Here, each alphabet is an element of the newly created array.

JavaScript Array of() Method

Example4

Using 'undefined' as an element of the Array.of() method.

Test it Now

Output:

It displays a new array with 'undefined' as its element.

JavaScript Array of() Method

Note: If we try to run this code in the web browser, it will not display 'undefined' as an array value. Thus, above snapshot shows the output of the console.

As discussed above, Array.of method creates constructor as an Array does, but the handling of integer arguments varies. For example, Array.of(10) will create an array holding 10 as its element. In the case of Array(10), it will create an array of length as 10.

Let's see the code implementation:

Simple Array Constructor Example

Output1: On console

The output shows an empty array with length 7.

JavaScript Array of() Method

Output2: On Browser

The output represents an empty array having length 7.

JavaScript Array of() Method

Array.of() Constructor Example:

Output:

JavaScript Array of() Method

Thus, the above examples will help to understand the difference between Array.of() and Array constructor.


Next TopicJavaScript Array





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA