What's the Difference Between "Array.of()" and "new Array()" in JavaScript?

The difference between using Array.of() and the Array constructor is how they both handle a single integer argument:

const x = Array.of(3);
const y = new Array(3);

console.log(x); // output: [3]
console.log(y); // output: array of 3 empty slots

console.log(x.length); // output: 1
console.log(y.length); // output: 3

As you can see from the example above, using the Array constructor with a single argument creates an empty array with its length property set, whereas Array.of() creates a new Array with a single element. However, if you were to supply multiple arguments to either, Array.of() or the Array constructor, they would both yield the same result. To demonstrate this, let's look at the following example:

const x = Array.of(1, 2, 3);
const y = new Array(1, 2, 3);

console.log(x); // output: [1, 2, 3]
console.log(y); // output: [1, 2, 3]

console.log(x.length); // output: 3
console.log(y.length); // output: 3

You may use Array(…) (as a function) and new Array(…) interchangeably as both are equivalent.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.