The Wayback Machine - https://web.archive.org/web/20250101010710/https://www.geeksforgeeks.org/javascript-array-of-method/
Open In App

JavaScript Array of() Method

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Javascript array.of() method is an inbuilt method in JavaScript that creates a new array instance with variables present as the argument of the method.

Syntax:

Array.of(element0, element1, ....)

Parameters: 

  • Parameters present are element0, element1, …. which are basically an element for which the array creation is done. 

Return Value: 

  • It simply returns a new Array instance. 

Example 1: Creating an Array with Numbers.

In this example, Creates an array with the numbers 1 to 5 using Array.of().

JavaScript
let numbersArray = Array.of(1, 2, 3, 4, 5);
console.log(numbersArray); 

Output
[ 1, 2, 3, 4, 5 ]

Example 2: Creating an Array with Different Types of Elements

In this example, Creates an array with mixed types: number, string, boolean, object, and array.

JavaScript
let mixedArray = Array.of(10, 'hello', true, { name: 'John' }, [1, 2, 3]);
console.log(mixedArray); 

Output
[ 10, 'hello', true, { name: 'John' }, [ 1, 2, 3 ] ]

Example 3: Creating an Array with Undefined and Null Values

In this example, Creates an array containing special values: undefined, null, NaN, and Infinity.

JavaScript
let specialValuesArray = Array.of(undefined, null, NaN, Infinity);
console.log(specialValuesArray); 

Output
[ undefined, null, NaN, Infinity ]

Supported Browsers:

  • Chrome 45
  • Edge 12
  • Firefox 25
  • Opera 26
  • Safari 9

JavaScript Array.of() Method – FAQs

What is the Array.of() method in JavaScript?

The Array.of() method creates a new Array instance with a variable number of arguments, regardless of the number or type of the arguments.

How does Array.of() differ from the Array constructor?

Array.of(7) creates an array with one element (7), while Array(7) creates an array with seven empty slots.

Can Array.of() handle mixed data types?

Yes, Array.of() can create arrays with mixed data types, including numbers, strings, booleans, objects, and arrays.

How does Array.of() handle single arguments?

Array.of(5) creates an array with one element [5], unlike Array(5) which creates an array with five empty slots.

Can I use Array.of() with non-primitive types?

Yes, Array.of() can include objects, arrays, functions, and other non-primitive types as elements.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript


Next Article

Similar Reads

three90RightbarBannerImg