119

What is the difference between each of the following array definitions.

var myArray = [];
var myArray = {};
var myArray = new Array();
Pinkie
  • 10,126
  • 22
  • 78
  • 124

2 Answers2

146

The first and third are equivalent and create a new array. The second creates a new empty object, not an array.

var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
Ben_Coding
  • 398
  • 6
  • 17
johusman
  • 3,472
  • 1
  • 17
  • 11
  • How do we access values of the object. – Pinkie Feb 26 '11 at 20:35
  • 3
    With brackets or dot notation: `myObject["someValue"]` or `myObject.someValue` . The empty object created by `{}` will of course not have those properties, but you can assign to them in the same way: `myObject.someValue = "hello!"` – johusman Feb 26 '11 at 20:39
  • 4
    In this particular case 1 and 3 have the same effect. Sometimes, however, they behave differently. For example, if `var a = new Array(5)` and `var b = [5]`, then `a` ≠ `b` (since `a.length` = 5 while `b.length` = 1, `a[0]` is `undefined` while `b[0]` is 5, and so on.) – Hunan Rostomyan Feb 07 '15 at 21:18
  • is `var a;` and `var a = {};` the same? – RNA Nov 11 '17 at 04:34
31

var myObject = {}; is equivalent to var myObject = new Object();

So, the second example is not an Array but a general Object.

This can get confusing as Array is a class and Object is a class - more precisely Array is a sub-class of Object. So, by and large, Object semantics are applicable to an Array:

var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value';  // define a custom property.
console.log(o.property1);
console.log(o.length);  // Outputs '2' as we've only push()'ed two elements onto the Array
leepowers
  • 37,828
  • 23
  • 98
  • 129
  • 2
    where is property1 stored. Is it not in the array – Pinkie Feb 26 '11 at 20:55
  • 10
    @Pinkie: This is getting confusing now: *Arrays are objects too*. By doing `o['property1'] = 'property value'`, you are not actually adding an element to the array, but setting a property of the *array object*. Confused? I told ya ;) In JavaScript, basically everything is an object. Other objects, like `Array`, `RegExp`,... extend the basic object with further functionality. A plain, empty object is created it with the curly brackets `plain_obj = {}`. – Felix Kling Feb 26 '11 at 21:00