Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between var = {} and var = []? [duplicate]

Tags:

javascript

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?

like image 665
Gil Birman Avatar asked Aug 23 '12 18:08

Gil Birman


2 Answers

[] 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}'
like image 65
Niet the Dark Absol Avatar answered Nov 05 '22 12:11

Niet the Dark Absol


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"]
    
like image 30
apsillers Avatar answered Nov 05 '22 11:11

apsillers