JavaScript Array of
Method (Live Playground)
The JavaScript array of
method is used to create a new Array instance with a variable number of arguments. These arguments represent the elements of the array.
Let's take a look at an example:
let newArray = Array.of(10, 20, 30, 40);
console.log(newArray);
// Expected output:
// [10, 20, 30, 40]
In the example, Array.of(10, 20, 30, 40)
creates a new array that includes the numbers 10, 20, 30, and 40.
Live Playground, Try it Yourself
You can create an array with a single element using the of
method too:
let newArray = Array.of('apple');
console.log(newArray);
// Expected output:
// ["apple"]
In this example, the new array contains only one element, "apple".
Live Playground, Try it Yourself
The of
method differs from the Array constructor. While the Array constructor creates an array with a single element when one argument is passed, the of
method creates an array with that argument as the only element:
let newArray = new Array(3);
console.log(newArray.length); // outputs: 3
let newArray2 = Array.of(3);
console.log(newArray2.length); // outputs: 1
Live Playground, Try it Yourself
Understanding of
can help you handle arrays more effectively in JavaScript.