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.
The syntax of Array of() method is as follows:
It takes and put elements in an array form. Thus, these elements create the array.
It returns a newly created array instance.
Let's implement some examples to understand better:
Here's an example that shows the working of Array of() method.Test it Now
The output represents the elements in the array form.
Here's an example to represent a single value in the form of an array.Test it Now
Here, 1 is a single element of the newly created array.
Example3Test it Now
Here, each alphabet is an element of the newly created array.
Using 'undefined' as an element of the Array.of() method.Test it Now
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:
Thus, the above examples will help to understand the difference between Array.of() and Array constructor.