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:

Array.of(element0, element1, ..., elementN)
  • 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 the Array constructor (i.e., new Array()) is how they handle numbers:
    • Array.of(7) creates an array with one element, the number 7.
    • new Array(7) creates an array with a length of 7 (an empty array with 7 slots).

Examples:

  1. Basic usage:

    console.log(Array.of(1, 2, 3)); // [1, 2, 3] console.log(Array.of('a', 'b', 'c')); // ['a', 'b', 'c']
  2. Single numeric argument:

    console.log(Array.of(7)); // [7] (array with one element) console.log(new Array(7)); // Array with 7 empty slots
  3. Mixed types:

    console.log(Array.of(1, 'hello', true, null)); // [1, 'hello', true, null]

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:

// Array.of(): console.log(Array.of(7)); // [7] // Array(): console.log(new Array(7)); // Array(7) [empty × 7]

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.