menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:of() method

menu

The method Array.of() is an inbuilt array method in JavaScript. This is a method to construct a new array containing specified elements.

The array can be programmatically created using the array of() method. The arguments of () method of array are treated as elements of an array and return an array with those elements. 

Let's explore the Array.of()the method in detail such as using it, its behavior and also considerations.

Basic Syntax of Array.of() method:

javascriptArray.of(element1, element2, ..., elementN);

From element1, element2 to elementN represents the elements of the new array.

Return Value of Array.of() method:

The Array.of() method returns a new array containing the specified elements we passed as arguments for Array.of() method.

Let's look at the uses of Array.of() method:

How can we create an Array with the same type of elements?

javascriptconst numbers = Array.of(1, 2, 3, 4, 5);

console.log(numbers); // Outputs: [1, 2, 3, 4, 5]

In the above last exampleArray.of()method created a new array with numbers.

How can we create an Array with different types of elements?

javascriptconst mixedData = Array.of(1, 'two', true, [3, 4], { name: 'Alice' });

console.log(mixedData);
// Outputs: [1, 'two', true, [3, 4], { name: 'Alice' }]

In the above example, the Array.of() method is used to create an array containing elements of different data types, including numbers, strings, booleans, arrays, and objects.

How can we create an empty Array?

javascriptconst emptyArray = Array.of();

console.log(emptyArray); // Outputs: []

We can create an empty array with the help of Array.of() method, if we do not pass any arguments in Array.of() method.

Additional Points:

  • Contrary to Array(), which behaves differently depending on the number and type of arguments, Array.of() always creates an array with the provided elements.

  • If you pass a single argument to Array.of(), it creates an array with one element which is that argument. However with Array(), only one argument is seen as the length of the array.

Performance Considerations:

The Array.of() method has a time complexity of O(N), where N is the number of elements specified. It produces an array with the mentioned items therefore the time it takes is proportional to the number of elements.

In conclusion, the Array.of() method is a simple means of creating a new array with the stipulated elements. Such a method often is applicable when you would like to enforce the argument to be elements and not for array lengths or fillings. It is a trustworthy selection for creating arrays with defined contents.

1280 x 720 px