11

Possible Duplicate:
Objects vs arrays in Javascript for key/value pairs

I have a variable in JavaScript which I am using like a hash. I can initialize it like:

var selected = [];

or

var selected = {};

and it does the same exact thing. I'm using it like this for example:

selected["one"] = 1;

if (selected["one"] == 1) console.log("one is selected"); 
// result: one is selected

if (selected["two"] != 1) console.log("two is not selected");
// result: two is not selected

selected["one"] = 0;

if (selected["one"] != 1) console.log("one is no longer selected");
// result: one is no longer selected

Is there really a difference? Is one an object and the other an array ? If so, when should I expect to run into problems. Ie., what is the difference between the two in their usage, and why would you chose one over the other?

Community
  • 1
  • 1
Gil Birman
  • 35,242
  • 14
  • 75
  • 119
  • 4
    possible duplicates: [Objects vs arrays in Javascript for key/value pairs](http://stackoverflow.com/questions/688097), [What is the difference between an array and an object?](http://stackoverflow.com/questions/874205), [JavaScript arrays braces vs brackets](http://stackoverflow.com/questions/5129544) – mellamokb Aug 23 '12 at 18:27
  • 2
    This happens because arrays in Javascript are objects too. So you can assign stuff to the array object's slots just like a plain object. – Cameron Aug 23 '12 at 18:30
  • 1
    Don't confuse array-like syntax with arrays. For example, in Javascript `selected["one"]` is equivalent to `selected.one` (the former supports arbitrary strings as keys, the latter alpha-numeric ones). – EthanB Aug 23 '12 at 18:38
  • Even if this is technically really just a duplicate of the difference of array and objects, for someone who doesn't know (or keeps on forgetting it) that {} is an object and [] is an array, this is a different question. Kinda like 2 is different from 'two'. – Gellie Ann Jul 01 '18 at 00:10

7 Answers7

20

[] is an array, {} is an object. An array is a type of object intended to be only assigned numeric keys.

While you can in theory use them interchangably, look what happens when you JSON-ify them:

var tmp = []; // or: var tmp = {}
tmp.one = 1;
JSON.stringify(tmp);

// array:
'[]'

// object:
'{"one":1}'
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
4

An Array ([]) is a kind of Object ({}). The key differences are:

  • Arrays have a magic length property that is equal to the highest-set numeric key (plus one):

    var a = [];
    a[100] = 0;
    a.length; // is 101
    
    var o = {};
    o[100] = 0;
    o.length; // is undefined
    
  • An Array's toString method prints out the values of numeric keys:

    var a = [];
    a[0] = 5;
    a[1] = 6;
    a[2] = 7;
    a.toString(); // "[5,6,7]"
    
    var o = {};
    o[0] = 5;
    o[1] = 6;
    o[2] = 7;
    o.toString(); // "[object Object]"
    
  • Arrays have lots of specific functions for processing records:

    > Object.getOwnPropertyNames(Array.prototype)
    ["join", "toLocaleString", "sort", "some", "lastIndexOf", "splice", "map",
     "constructor", "every", "unshift", "shift", "indexOf", "pop", "forEach", "reverse",
     "reduce", "slice", "concat", "filter", "toString", "reduceRight", "push", "length"]
    
apsillers
  • 112,806
  • 17
  • 235
  • 239
2

Yup, {} is an empty object and [] is an empty array. Note that an array is a kind of object, optimized to handle a list of values, but, like any Javascript object, it can accept other attributes like "one" or "two" — which is how it can support methods like myArray.push(1): push is an attribute of all arrays. In fact, you can even say myArray["push"] = someOtherFunction to override push without any trouble. Arrays, like all Javascript objects, support arbitrary key-value assignments.

Ultimately, though, it has to do with behind-the-scenes performance. If you're looking to store a sequential list of values, the array will handle it much better and offer some helpful attributes like push, shift, length, etc. — plus, future developers will actually know what you're doing. If you're looking to just store key-value pairs, the object is the way to go, since it's not bogged down by all that extra weight.

In short, while they both support key-value pairs, they're very different behind the scenes. Don't worry too much about it and use whichever lends itself better to the job at hand.

Matchu
  • 83,922
  • 18
  • 153
  • 160
0

Using {} is an object, which is the basis for every complex type in Javascript. The reason you can treat an array like an object is because in Javascript an array is an object (but not the other way around).

The square brackets in Javascript are the way you access an object's attributes, much like the . notation in C, Java, Python, etc. It just so happens that arrays have values at attribute 0, 1, 2, etc. Arrays also have a whole bunch of other built-in attributes like length, shift, push, etc.

This is an oversimplification for sure, however it's an easy way to understand what's going on.

robbrit
  • 17,560
  • 4
  • 48
  • 68
0

An Array is an Object, but an Object is not (always) an Array. An Array has methods and properties not present in every object Example

[].length //0
{}.length //undefined
typeof []['slice'] //function
typeof {}['slice'] //undefined

If you use an array as a hashmap and try to use as a key something already present you will get into trouble

Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29
0

[] is for arrays and {} is for plain objects. Note that an array is an object with a number of methods and properties that allow to model lists (e.g. push, slice, ...).

As pointed out in the MDN documentation, you shouldn't use an array as an associative array, i.e. arrays are not to be used as hash tables.

Bruno
  • 119,590
  • 31
  • 270
  • 376
-1

The first is an array, the second is a literal object:

var a = {};
a.SomeProperty = 1;

console.log(a.SomeProperty);

var b = [];
b['SomeProperty'] = 2;

console.log(b['SomeProperty']);

This will output 1 and 2 in the console logs.

For hashing, use an array (WRONG), thanks for the comment.

Novak
  • 2,760
  • 9
  • 42
  • 63
  • 2
    -1 for "For hashing, use an array" – kapa Aug 23 '12 at 18:32
  • Why is that? I'm actually interested in your answer, since that what I was doing until now. – Novak Aug 23 '12 at 18:47
  • 1
    An array is best used for numerically indexed storage (`var a = []; a[0] = 1;`). If you want a hash, an array has nothing more to offer than a simple object (`var a = {}; a['prop'] = 1;`) - and it can even have drawbacks you might not expect (like the JSON representation in Kolink's answer). – kapa Aug 23 '12 at 18:55