Javascript - Array of() method

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


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.


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

const arr2 = Array(10); // w ww  .  j av a  2  s .co  m
console.log(arr2); // [,,,,,,,,,] 
console.log(arr2.length);      // 10


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