Javascript - Array of() method

Array.of() creates an array of elements more easily.

Description

Array.of() creates an array of elements more easily.

Array.of() takes a list of items as parameters and returns them to you as an array.

let arr = Array.of(10, 20, 30, 40); 
console.log(arr); // [10, 20, 30, 40] 

When passing one parameter into Array constructor, instead of making an array of one element with that number value, it constructs an empty array with the number as its length.

All the elements are set to undefined.

The Array.of() static method fixes this issue and is now the preferred function-form constructor for arrays.

Demo

const arr1 = Array.of(10); 
console.log(arr1); // [10] 
console.log(arr1.length);      // 1 

const arr2 = Array(10); /*from  w w w  . ja  va  2  s  . c om*/
console.log(arr2); // [,,,,,,,,,] 
console.log(arr2.length);      // 10

Result

Here, the Array.of(10) creates an array of single number [10], whereas new Array(10) method creates an empty array of length 10.