The Array.of() method in JavaScript creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
There are 4 variations for the syntax of Array.of() static-method. They are:
Array.of()
This static-method creates a new empty array.
Returns value of type Array
.
Array.of(element1)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to include in the array. |
This static-method creates a new array with one element.
Returns value of type Array
.
Array.of(element1, element2)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to include in the array. |
element2 | required | The second element to include in the array. |
This static-method creates a new array with two elements.
Returns value of type Array
.
Array.of(element1, element2, /* …, */ elementN)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to include in the array. |
element2 | required | The second element to include in the array. |
elementN | optional | Additional elements to include in the array. |
This static-method creates a new array with one or more elements.
Returns value of type Array
.
In JavaScript, we can use the Array.of() method to create a new empty array.
For example,
const emptyArray = Array.of();
console.log(emptyArray);
[]
We can use the Array.of() method to create a new array with one element.
For example,
const singleElementArray = Array.of(1);
console.log(singleElementArray);
[1]
We can use the Array.of() method to create a new array with multiple elements.
For example,
const multipleElementsArray = Array.of(1, 2, 3);
console.log(multipleElementsArray);
[1, 2, 3]
In this JavaScript tutorial, we learned about of() static-method of Array: the syntax and few working examples with output and detailed explanation for each example.