JavaScript Array of() Method

The of() method creates a new array instance from the given arguments.

Example

// creating an array named alphabets with elements A,B,C let alphabets = Array.of("A", "B", "C");
// display contents of alphabet' console.log(alphabets); // Output: [ 'A', 'B', 'C' ]

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 Array instance.

Example 1: Using of() method

// creating an array 1 element let numbers = Array.of(3);
console.log(numbers); // [ 3 ]
// creating an array with 3 string elements let fruits = Array.of("Apple", "Banana", "Grapes");
console.log(fruits); // [ 'Apple', 'Banana', 'Grapes' ]
// creating an array with 4 integers let primeNumbers = Array.of(2, 3, 5, 7);
console.log(primeNumbers); // [ 2, 3, 5, 7 ]

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:

// creating an array with one element using Array.of() let evenNumber = Array.of(2);
// displays the length of evenNumber console.log(evenNumber.length); // 1 // displays content inside evenNumber console.log(evenNumber); // [2]
// creating an empty array of length 2 using Array constructor let numbers = Array(2);
// displays the length of 'numbers' array console.log(numbers.length); // 2 // displays the content inside 'numbers' console.log(numbers); // [ <2 empty items> ]

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.


Also Read:

Did you find this article helpful?