2
var foo = {}
var bar = new Array();
var another = [];

Also, is it possible to add to foo like so:

foo['obj'] = new Date();
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
Sean
  • 779
  • 6
  • 18

5 Answers5

5
var foo = {};

foo is an object literal.

var bar = new Array();

bar is an array initialized via the Array constructor.

var another = [];

another is an array literal. Creating new arrays through literals is more efficient than doing so through the Array constructor: http://jsperf.com/new-array And it’s also much easier to type ;) I’d recommend using array literals wherever possible.

Also, is it possible to add in foo like so: foo['obj'] = new Date();

Yes. That will add a property obj to foo with the value of new Date(). It’s equivalent to foo.obj = new Date();.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
1

foo is an object, not an array. bar and another are arrays.

if you give foo['obj'] = new Date();, obj will become a property of foo.

Diode
  • 24,570
  • 8
  • 40
  • 51
1

var foo = {}

This is an object, not an array.

var bar = new Array();

This is array but avoid new keyword with arrays.

var another = [];

This is correct way of initializing array.

Also, is it possible to add in foo like so: foo['obj'] = new Date();

There is no associative array in JS. You can instead do:

var foo = {};
var foo['obj'] = new Date();
Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • “There is no associative array in JS.” No, but you can add key-value pairs to arrays: `var array = []; array.foo = 42; console.log(array, array.foo); // logs [] and then 42`. – Mathias Bynens Feb 16 '12 at 07:30
  • @MathiasBynens: That's true but this clears the confusion most devs have with it :) – Sarfraz Feb 16 '12 at 07:31
0

bar and another are the same, but:

var foo = {}; 

foo is not an array rather an object

foo['obj'] = new Date(); //same as
foo.obj = new Date();

the advantage of f['obj'] is that you can use non-valid identifier characters ex:

   foo['test-me'] // is valid
   foo.test-me //not valid
jerjer
  • 8,694
  • 30
  • 36
0
var foo = {} is for object referal,
    foo = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales}

while var bar = new Array(); is used to create new empty array.

But var another = []; can be used to assign any array empty values as well as creates empty array. I think for date you can use like foo[1] = new Date();

Parag Gajjar
  • 700
  • 1
  • 11
  • 25