JavaScript Array.of() method
The Array.of()
method in JavaScript creates a new array instance from a variable number of arguments, regardless of the number or types of the arguments.
Syntax:
element0, element1, ..., elementN
: The elements used to create the array.
Description:
Array.of()
creates an array containing the provided elements in the exact order.- The key difference between
Array.of()
and theArray
constructor (i.e.,new Array()
) is how they handle numbers:Array.of(7)
creates an array with one element, the number7
.new Array(7)
creates an array with a length of7
(an empty array with 7 slots).
Examples:
Basic usage:
Single numeric argument:
Mixed types:
Difference between Array.of()
and Array()
:
Array.of()
ensures that you always get an array with the provided elements, regardless of whether you pass a single number or multiple elements.Array()
behaves differently when you pass a single number—it creates an empty array with that number as the length, not an array containing that number as an element.
Example Comparison:
Summary:
Array.of()
creates an array from any number of arguments and ensures that even if a single number is passed, it is treated as an element.- It's useful for creating arrays consistently, without the quirks of the
Array()
constructor when dealing with numeric arguments.