What does Array.of() do?
The Array.of() method creates a new array from any number of passed arguments,
regardless of their type and count.
It solves one important inconsistency in the behavior of the Array() constructor.
Example:
javascript
const arr = Array.of(1, 2, 3);
console.log(arr); // [1, 2, 3]Each argument becomes a separate element of the new array.
The problem with Array():
If you call Array() with a single number, it does not create an array with that number,
but an empty array of the given length:
javascript
Array(3); // [ <3 empty items> ]
Array.of(3); // [3]
Array.of()always creates the array "as is", whileArray(3)treats 3 as "the length of the array".
Syntax:
javascript
Array.of(element1, element2, ..., elementN);| Parameter | Description |
|---|---|
elementN | The elements that will go into the new array |
Usage examples:
One element
javascript
Array.of(5); // [5]Several elements
javascript
Array.of(1, 2, "JS", true); // [1, 2, "JS", true]No arguments
javascript
Array.of(); // []Difference from Array.from()
| Method | What it does |
|---|---|
Array.of() | Creates an array from arguments |
Array.from() | Creates an array from an iterable object (for example, a string, Set, NodeList) |
Example of the difference:
javascript
Array.of("a", "b", "c"); // ["a", "b", "c"]
Array.from("abc"); // ["a", "b", "c"]In short:
| What it does | Creates an array from the passed values |
|---|---|
| Returns | A new array |
| Changes the source data | No |
Solves the problem with Array(number) | Yes |
| Example | Array.of(3) -> [3], not [ <3 empty items> ] |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.