JavaScriptArrays

Array.of()

Creates a new array from the given arguments, regardless of how many there are or their type.

Returns
A new array with the given elements.
Changes the original
No
On this page

Example

#
JavaScript
console.log(Array.of(7))
console.log(Array.of(1, 2, 3))
console.log(Array.of('HTML', 'CSS'))
console.log(Array.of())
Console
[7]
[1, 2, 3]
['HTML', 'CSS']
[]

Definition and usage

#

The static Array.of() method creates an array whose elements are exactly the arguments you pass. Array.of(7) gives an array with one element, 7, and Array.of(1, 2, 3) gives an array of three numbers.

It exists to work around an odd quirk of the Array constructor. Calling new Array(3) with a single number doesn’t create the array [3]; it creates an empty array of length 3, and new Array(2.5) throws an error. Array.of() always treats its arguments as elements.

Day to day, arrays are created with the literal [1, 2, 3], which is shorter and clearer. Array.of() is useful where you need a function that builds an array from arguments, and in classes that extend Array, since it returns an instance of that class.

Syntax

#
Syntax
Array.of(element1, element2, …)

Parameters

#
  • element1…elementN

    any values

    The values that become the array’s elements. With no arguments, you get an empty array.

More examples

#
Array.of() vs. the Array constructor
JavaScript
console.log(new Array(3).length)
console.log(Array.of(3).length)
console.log(new Array(3, 4))

try {
  new Array(2.5)
} catch (error) {
  console.log(error.name)
}
Console
3
1
[3, 4]
RangeError

The Array constructor treats a single number as a length, and several arguments as elements. Array.of() doesn’t have that inconsistency.

Pitfall: Array.of as a callback
JavaScript
const tags = ['html', 'css']

console.log(tags.map((tag) => Array.of(tag)))
console.log(tags.map(Array.of))
Console
[['html'], ['css']]
[['html', 0, ['html', 'css']], ['css', 1, ['html', 'css']]]

map() also passes the index and the whole array to the function, and Array.of turns every argument into an element. Wrap the call in an arrow function so only one argument gets passed.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For everyday array creation, use the literal []. Reach for Array.of() when you need it as a function.
  • Don’t create an array with new Array(n) if you want an array containing the number n. You’ll get an empty array of length n.
  • For an array of known length filled with values, Array.from({ length: n }, fn) is better.

Related entries

#

Spotted a mistake or missing an example? Write to us.