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
Example
#console.log(Array.of(7))
console.log(Array.of(1, 2, 3))
console.log(Array.of('HTML', 'CSS'))
console.log(Array.of())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
#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
#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)
}The Array constructor treats a single number as a length, and several arguments as elements. Array.of() doesn’t have that inconsistency.
const tags = ['html', 'css']
console.log(tags.map((tag) => Array.of(tag)))
console.log(tags.map(Array.of))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 forArray.of()when you need it as a function. - Don’t create an array with
new Array(n)if you want an array containing the numbern. You’ll get an empty array of lengthn. - For an array of known length filled with values,
Array.from({ length: n }, fn)is better.
Related entries
#- Array.from()Creates an array from an iterable or "array-like" object.
- Array.isArray()Checks whether a value is an array.
- Array.prototype.fill()Fills an array (or part of it) with a single value.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.