Array.prototype..of()
Array.of(...elements) Returns:
Array · Updated March 13, 2026 · Array Methods array creation es6
Array.of() creates a new Array instance from a variable number of arguments, regardless of the number or type of arguments. Unlike the Array constructor, Array.of() does not treat a single number argument as an array length — it creates an array with that single element.
Syntax
Array.of(element0)
Array.of(element0, element1)
Array.of(element0, element1, ...elementN)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
elements | any | — | Any number of values to include in the new array |
Examples
Basic usage
const arr = Array.of(1, 2, 3);
console.log(arr);
// [1, 2, 3]
// Single number is treated as element, not length
const single = Array.of(5);
console.log(single);
// [5]
// Works with any type
const mixed = Array.of(1, 'two', true, null);
console.log(mixed);
// [1, 'two', true, null]
Comparing Array.of() vs Array constructor
// Array.of() - treats argument as element
const withOf = Array.of(3);
console.log(withOf.length); // 1
console.log(withOf); // [3]
// Array() constructor - treats single number as length
const withConstructor = Array(3);
console.log(withConstructor.length); // 3
console.log(withConstructor); // [empty × 3]
// This is the key difference - Array.of() avoids this gotcha
Creating arrays from array-like objects
// Convert arguments object to array
function greet() {
const args = Array.of(...arguments);
console.log(`Hello, ${args.join(' and ')}!`);
}
greet('Alice', 'Bob', 'Carol');
// Hello, Alice and Bob and Carol!
// Ensure consistent array creation
const numbers = Array.of(...[1, 2, 3]);
console.log(numbers);
// [1, 2, 3]
Common Patterns
Array.of() is particularly useful when you need to create an array in scenarios where the Array constructor could behave unexpectedly:
- Type-safe array creation: Always creates an array with the exact elements passed
- Functional programming: Useful as a way to ensure values are wrapped in an array
- Converting iterables: Works with spread operator to convert any iterable
See Also
- array::from — creates array from array-like or iterable
- array::isArray — checks if value is an array