• JavaScript Video Tutorials

JavaScript - Array .of() Method



In JavaScript, the Array.of() method creates a new Array instance with a variable number of arguments, regardless of their datatype. It is similar to the Array() constructor, but it differs in the way it handles single arguments. Here's how it works −

Single Argument Handling

  • Array.of(5) − Creates a new array with a single element of value 5.
  • Array(5) − Creates an empty array with a lenght of 5.

Multiple Arguments Handling

  • Array.of(1, 2, 3) − Creates a new array with three elements: 1, 2, and 3.
  • Array(1, 2, 3) − Also creates a new array with three elements: 1, 2, and 3.

Empty Arguments Handling

  • Array.of() − Creates a new empty array.
  • Array() − Also creates a new empty array.

Syntax

Following is the syntax of JavaScript Array.of() method −

Array.of(element1, element2, ..., elementN)

Parameters

This method accepts one or more elements. These can be any data type.

Return value

This method returns a new Array instance.

Examples

Example 1

In the following example, we are using the Array.of() method to create an array of numbers with the elements 1, 2, 3, 4, and 5.

<html>
<body>
   <script>
      const numbers = Array.of(1, 2, 3, 4, 5);
      document.write(numbers);
   </script>
</body>
</html>

If we execute the above program, it returns all the elements exist in the array.

Output

1,2,3,4,5

Example 2

Here, the Array.of() method is used to create an array of strings with the elements 'apple', 'banana', and 'cherry' −

<html>
<body>
   <script>
      const fruits = Array.of('apple', 'banana', 'cherry');
      document.write(fruits);
   </script>
</body>
</html>

After executing the above program, it returns all the elements exist in the array.

Output

apple,banana,cherry

Example 3

Following examples demonstrates the difference between Array.of() and the Array() constructor is in the handling of single arguments −

<html>
<body>
   <script>
      const arr1 = Array.of(5); //[5]
      const arr2 = Array(5); // array of 5 empty slots
   </script>
</body>
</html>

In the above program, 'arr1' will create an array with a single element [5], whereas 'arr2' creates an empty array with a lenght of 5.

Example 4

Following examples demonstrates the difference between Array.of() and the Array() constructor is in the handling of multiple arguments −

<html>
<body>
   <script>
      const arr1 = Array.of(1, 2, 3);
      const arr2 = Array(1, 2, 3);
      document.write(arr1, "<br>", arr2)
   </script>
</body>
</html>

In the above program, 'arr1' and 'arr2' will create arrays with three elements [1, 2, 3].

Output

1,2,3
1,2,3

Example 5

If we do not provide any elements to the Array.of() method, it creates an empty array −

<html>
<body>
   <script>
      const arr1 = Array.of(); //[]
      const arr2 = Array(); //[]
   </script>
</body>
</html>

If we execute the above program, both will create a new empty arrays.

Advertisements