JavaScript Array of() Method
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().
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.
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.
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), whileArray(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], unlikeArray(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.


