0

What is the difference between creating an array with Array(0) and array = []?

To my knowledge both are empty Array objects.

array
>>> []
Array(0)
>>> []

But when I compare them they return 'false'.

var array = []
array === Array(0)
>>> false

What's going on here??

tbd_
  • 1,058
  • 1
  • 16
  • 39

4 Answers4

2

To my knowledge both are empty Array objects.

They are

But when I compare them they return 'false'.

When you compare two objects in JavaScript you are testing to see if they are the same object, not if they are identical objects.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

2 arrays (even empty) can't be compared this way and be equal.

Here's the answer how to compare 2 arrays in a proper way: How to compare arrays in JavaScript?

Julia
  • 95
  • 1
  • 7
1

Because arrays are objects, not primitives :

var x = 5; // primitive
var y = 5; // primitive
console.log(x == y); // True
var x = [5]; // object
var y = [5]; // object
console.log(x == y); // False
var x = '5'; // primitive
var y = '5'; // primitive
console.log(x == y); // True
var x = {0:5}; // object
var y = {0:5}; // object
console.log(x == y); // False

About the difference, Check this question's answers (The accepted and the second one) : What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
And more on primitives and objects : object vs. primitive

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1
var p = Array(0); // []
[] var p = []   // []

Both work the same way to create an empty array.

var p = Array(3); //[undefined, undefined, undefined]

Which you can also do using :

var p = [undefined, undefined, undefined];

Again both work the same way internally but have different use cases :

For ex. If you want to create an array with n elements :

var array = new Array(n) // [undefined * n]

If you want to initialise values of arrays while creation :

var arry = [1,2,3,4];

One thing to note here is you can create an initialized array with new Array() as well :

var p = new Array(1,2,3,4); // [1,2,3,4]

But when you try to create an array with one initialised value it takes that one parameter and create an array of that size :

var p = new Array(4)  // [undefined*4]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Manoj
  • 1,175
  • 7
  • 11