The Array.of(values…) method

The Array.of() method is an alternative to the Array constructor for creating arrays. When using the Array constructor, if we pass only one argument, that too a number, then the Array constructor constructs an empty array with the array length property equal to the passed number instead of creating an array of one element with that number in it. Therefore the Array.of() method was introduced to resolve this issue.

Here is an example to demonstrate this:

let arr1 = Array(2);let arr2 = Array.of(2);console.log(arr1);console.log(arr2);

The output is as follows:

[undefined, undefined][2]

You should use Array.of() instead of an Array constructor when you are constructing a new array instance dynamically, that is when ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.