Array.prototype.of() method is used to create a new array from a variable number of arguments, holding any type of argument.
array.of(element1, element2, …,elementN);
This method takes no. of N elements as a parameter to create an array as given below:
The main difference between the
Array.of() and the Array constructor is the handling of the arguments.
In ES5, when you pass a number to the Array constructor, it creates an array whose length equals the number you passed. But when you passed a value other than the number then the array Array constructor creates an array that contains one element with the same value you passed as the constructor argument.
This behavior of the Array constructor is very confusing and error-prone. To overcome this issue, ES6 introduces the
Array.of() method to solve this problem. When you pass any argument to
Array.of() method it always creates an array with that element.
Here are some examples of
//Examples of Array.of() method console.log(Array.of(1)); // Output =>  console.log(Array.of(1, 2, 3)); // Output => [1, 2, 3] console.log(Array.of(undefined)); // Output => [undefined] //Difference between Array.of() and Array Constructor console.log(Array.of(1)); // Output =>  console.log(new Array(1)); // Output => [empty] console.log(Array.of("1")); // Output => ["1"] console.log(new Array("1")); // Output => ["1"]
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!