;

Javascript Array - of() Method


Tutorialsrack 15/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.of(). How does this method work in javascript? 

Array.prototype.of()

The Array.prototype.of() method is used to create a new array from a variable number of arguments, holding any type of argument.

Syntax
array.of(element1, element2, …,elementN);

This method takes no. of N elements as a parameter to create an array as given below:

  • elementN:  Element used to create an array.

Array.of() Method and Array Constructor. 

Now we have a question, why do we need the Array.of() Method when we have an Array constructor to create an array?

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 Array.prototype.of() method:

Syntax
//Examples of Array.of() method
console.log(Array.of(1));
// Output => [1]

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 => [1]

console.log(new Array(1));
// Output => [empty]

console.log(Array.of("1"));   
// Output => ["1"]

console.log(new Array("1"));
// Output => ["1"]

I hope this article will help you to understand the javascript Array built-in method Array.prototype.of()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags