The of function generates and returns a new array composed of various arguments. It does not emphasize the type or quantity of the arguments provided. Like the Array constructor, it features a constructor that processes integer arguments, but it operates in a distinct way.
Syntax
The syntax of Array of method is as follows:
Array.of(element1, element2,.....)
Parameter
It takes elements and organizes them into an array format. Consequently, these elements collectively form the array.
Return
It returns a newly created array instance.
JavaScript Array of Method Example
Let's explore a few examples to gain a clearer understanding:
Example1
Below is an illustration demonstrating the functionality of the Array of method.
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
document.write(Array.of(1,2,3,4)); //values separated by commas.
</script>
</body>
</html>
Output:
The output illustrates the components in the format of an array.
Example2
The following example illustrates how to express a singular value as an array.
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
document.write(Array.of(1));
</script>
</body>
</html>
Output:
In this instance, 1 represents an individual element of the array that has just been generated.
Example3
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
document.write(Array.of("a","b","c","d"));
</script>
</body>
</html>
Output:
In this instance, every letter represents an individual component of the newly formed array.
Example4
Utilizing 'undefined' as a component within the Array.of function.
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
console.log(Array.of(undefined)); //using console
</script>
</body>
</html>
Output:
It shows a newly created array containing 'undefined' as its sole 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 previously mentioned, the Array.of method functions similarly to an Array constructor; however, the way it processes integer arguments differs. For instance, when invoking Array.of(10), it produces an array containing 10 as its sole element. Conversely, calling Array(10) generates an array with a length of 10.
Let's see the code implementation:
Simple Array Constructor Example
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
console.log(Array(7)); //using console
</script>
</body>
</html>
Output1: On console
The output shows an empty array with length 7.
Output2: On Browser
The result indicates an array that is empty, with a total length of 7.
Array.of Constructor Example:
<html>
<head>JavaScript Array Methods </head>
<body>
<script>
document.write(Array.of(7));
</script>
</body>
</html>
Output:
Consequently, the preceding examples serve to clarify the distinction between Array.of and the Array constructor.