Array.of() in JavaScript ES6

In this post, we are going to understand Array.of() in JavaScript ES6 with examples. “The Array.of() method creates a new  Array constructor from a variable number of arguments, regardless of the number or type of the arguments. The main difference between Array.of() and the Array constructor is in the handling of integer arguments: Array.of(9) creates an array with a single element, 9, whereas Array(9) creates an empty array with a length property of 9.

Problem with Array constructor in ES5


In ES5, passing a single numeric value to the array constructor creates an empty array whose size is equal to the number. As we can see, In the below code, we are creating a myarray bypassing numeric value 5 to the array constructor. It created an empty array of length 5. whereas accessing value at index 0 returns undefined.

let myarray = new Array(5);
console.log('array length =',myarray.length); 
console.log('accessing value at first index =',myarray[0]); 

Output

array length = 5
accessing value at first index = undefined

Note: This behavior is different when we pass a non-numeric value to the array constructor. It creates a non-empty array with a passed value. This is the strange and error-prone behavior of the array constructor.

let myarray = new Array('5');
console.log('array length =',myarray.length); 
console.log('accessing value at first index =',myarray[0]); 

Output

array length = 1
accessing value at first index = 5

1. ES6 Array.of()


In the ES6 method Array.of () is introduced to overcome the problem with the array constructor.Array.of() is similar to Array constructor except it creates a new array instance from a variable or number of arguments, no matter number or type of arguments.

Syntax

Array.of(element0 [, element1[, ...[, elementN]]])

Parameters

  • Parameters: element0 …..elements are elements that are used to create an array.
  • Return Value: It returns a new array instance.

Example

let myarray =  Array.of(5);
console.log('array length =',myarray.length); 
console.log('accessing value at first index =',myarray[0]);

Output

array length = 1
accessing value at first index = 5