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.
Output:
The output represents the elements in the array form.
Example2
Here’s an example to represent a single value in the form of an array.
Output:
Here, 1 is a single element of the newly created array.
Example3
Output:
Here, each alphabet is an element of the newly created array.
Example4
Using ‘undefined’ as an element of the Array.of() method.
Output:
It displays a new array with ‘undefined’ as its element.
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.
Output2: On Browser
The output represents an empty array having length 7.
Array.of() Constructor Example:
Output:
Thus, the above examples will help to understand the difference between Array.of() and Array constructor.