The Array.of() method in JavaScript is used to create a new array instance with a variable number of arguments, regardless of the number or types of the arguments. This method is useful for creating arrays from a set of values without the unexpected behavior that can occur with the Array constructor when a single numeric argument is passed.
Syntax
Array.of(element0, element1, /* …, */ elementN);
Parameters
Parameter | Description |
---|---|
element0, element1, /* …, */ elementN | These elements are used to initialize the array. |
Return Value
Return Type | Description |
---|---|
Array Object | It returns a new array instance containing the given elements. |
Example 1: Creating an Array with Multiple Elements
This code creates an array with the elements 1, 2, and 3 using the Array.of() method and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = Array.of(1, 2, 3); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: 1, 2, 3
Array Size: 3
Example 2: Creating an Array with a Single Numeric Element
This code creates an array with a single element 5 using the Array.of() method and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = Array.of(5); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: 5
Array Size: 1
Example 3: Creating an Array with Mixed Elements
This code creates an array with the elements 1, “hello”, and true using the Array.of() method and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = Array.of(1, "hello", true); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: 1, hello, true
Array Size: 3
Example 4: Creating an Empty Array
This code creates an empty array using the Array.of() method and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = Array.of(); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array:
Array Size: 0
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 25 | 32 | 9 |