menu

Weird behaviour of “new Array()” in Javascript?

Amit

TreeImage
TreeImage

When I’m playing around with Javascript arrays, I have noticed some weird behavior of an array constructor. Let’s look into it deeply.


How to create a JavaScript Array?
In Javascript, we can create an array using either

  • Array literals or
  • Array Constructor

Let’s start with the best way: Array Literals
I as a developer, regularly use this way:

var arr = [1,2,3]; // an array with three elements var arr = [1]; // an array with one element

Well, this is pretty much easy and we don’t have any problem with this way. Now, let’s look into another way: Array constructor

var arr = new Array(1,2,3); // an array with three elements var arr = new Array(3); // an empty array with length three

Did you find anything awkward? YES.

Here var arr = new Array(3);   gives an empty array with length 3, instead of an array with a single element.

To get over this problem, ES6 Introduced a new method Array.of()

The Array.of() method creates a new Array instance with specified number of arguments, regardless of number or type of the arguments.
The difference between Array.of() and the Array constructor is in the handling of integer arguments:

Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7

Note: This implies an array of 7 empty slots, not slots with actual undefined values.

Array.of(7); // an array with one element i.e. [7] Array.of(1, 2, 3); // an array with three elements i.e. [1, 2, 3]

Happy Coding 🙂

butterfly
Let'sTalk
butterfly
Thanks for the submission.