Array.of()

The Array.of() method in JavaScript creates a new array instance from the provided arguments, regardless of the number or types of the arguments.

Syntax

</>
Copy
Array.of()
Array.of(element1)
Array.of(element1, element2)
Array.of(element1, element2, /* …, */ elementN)

Parameters

ParameterDescription
element1, element2, ..., elementNElements used to create the new array. These can be of any type (numbers, strings, objects, etc.).

Return Value

The Array.of() method returns a new array containing the provided elements in the same order as they were passed.


Examples

1. Creating an Array with Multiple Elements

This example demonstrates how Array.of() creates an array from multiple elements.

</>
Copy
const numbers = Array.of(1, 2, 3, 4, 5);
console.log(numbers);

Output

[1, 2, 3, 4, 5]
  1. Array.of(1, 2, 3, 4, 5) creates an array containing the elements 1, 2, 3, 4, 5.

2. Creating an Array with a Single Element

Unlike the Array constructor, Array.of() always creates an array with a single element if only one argument is provided.

</>
Copy
const singleElement = Array.of(42);
console.log(singleElement);

Output

[42]

The array contains the single element 42.

3. Handling Different Data Types

The Array.of() method can handle elements of different data types.

</>
Copy
const mixedArray = Array.of(1, "two", { key: "value" }, [4, 5]);
console.log(mixedArray);

Output

[1, "two", { key: "value" }, [4, 5]]

The resulting array contains a number, a string, an object, and another array.

4. Comparing Array.of() with the Array Constructor

Unlike Array.of(), the Array constructor creates an array with a specific length if given a single numeric argument.

</>
Copy
// Using Array.of()
const arrayOf = Array.of(3);
console.log(arrayOf);

// Using Array constructor
const arrayConstructor = Array(3);
console.log(arrayConstructor);

Output

[ 3 ]
[ <3 empty items> ]
  1. Array.of(3) creates an array with a single element 3.
  2. Array(3) creates an array with a length of 3, containing empty slots.