Deqing Deqing - 10 months ago 25
Javascript Question

Should I use curly brackets {} or square brackets [] in this case?

Currently I have an array using an increasing index:

var idx = 1;
var a = [];
a[idx++] = "apple";
a[idx++] = "orange";

And only accessing it by
, not using array specific functions, like
, ...

Apparently following is also working in this case:

var a = {};

So, which one should I prefer in such case? For example any performance difference between them?


[ ] denotes an array. Arrays only hold values:

var a1 = [1, 2, 3, 4]

As @Qantas pointed out, array can hold more than just values. An array can even contain another array and/or object:

var a2 = [1, 2, ["apple", "orange"], {one: "grape", two: "banana"}];

{ } denotes an object. Objects have key-value pairs like

var a3 = {one: 1, two: 2}

In your case, it's really a matter of how you would like to be able to access the data. If you are only interested in knowing "apple", "pear", etc. Go ahead and use an array. You can access it via it's index

a1[0]; // outputs 1
a1[1]; // outputs 2

or you can iterate over it with a loop. If you use the curly braces, (given the example I gave) you could access it with; // outputs 1
a3["two"]; // outputs 2

It's really up to you on how it would best fit your needs in this case. For a more extensive discussion see this article.