Create a new array instance using Array.of() Method

In this section we will look at how to create an array using the Array.of() method and how it differs from the Array constructor.

Array.of() method is used for creating a new instance of an array. It takes as an argument one or more elements. The elements can be of different types.

Before looking at Array.of method, let us first look at creating an array using the constructor.

> let array = new Array(4);

The above statement will create an empty array of length 4.

Using the Array.of() method:

> let array = Array.of(4);
> array

We see that it creates a new array with one element of value 4 instead of creating 4 empty elements. This is the difference between Array.of and Array constructor if we pass an integer to it.

However, if we try to pass a string data type, for example, both have the same behaviour.

> a =  new Array("Javascript")
> a


> a = Array.of("Javascript")
> a

More examples on Array.of()

We have so far seen how to pass a single value to the Array.of method. However, we are not restricted to only one value. The method can also take multiple values.

> let a = Array.of(1, 2, 3, 4, 5, 6)
> a
[1, 2, 3, 4, 5, 6]

We can also specify different data types to the Array.of() method:

> let a = Array.of(1, "js", 2.5, {name: "mickey"})
> a
[1, 'js', 2.5, {…}]