The of() method creates a new Array instance from the given arguments.
Example
of() Syntax
The syntax of the of() method is:
Array.of(element0, element1, ..., elementN)
The of() method, being a static method, is called using the Array class name.
of() Parameters
The of() method can take n number of parameters:
- n specifies the number of elements inside the new array.
of() Return Value
- Returns a new
Arrayinstance.
Example 1: Using of() method
Output
[ 3 ] [ 'Apple', 'Banana', 'Grapes' ] [ 2, 3, 5, 7 ]
In the above example, we are using the of() method to create array: numbers, fruits, and primeNumber respectively.
We have called the of() method in Array class as Array.of() and have passed different numbers and strings as parameters.
Example 2: Array of() Method and Array Constructor
The difference between the Array.of() and the Array constructor is the handling of the arguments.
On passing a number to the Array constructor creates a new array with length equal to number.
However in the Array.of() method if we pass any number it creates array with that number as an element. For example:
Output
1 [ 2 ] 2 [ <2 empty items> ]
Here Array.of(2) creates an array [2] with length 1 and 2 as it's element and Array(2) creates an empty array [ <2 empty items> ] with length 2.
Recommended Reading: JavaScript Array