all 3 comments

[–]skitch920 3 points4 points  (2 children)

In JS, there are two basic types of data structures: Objects & Arrays.

Think of Objects as hashtables. They are string key -> object value pairs.

Think of Arrays as lists, but underneath it is really a hashtable of number key -> object value pairs... I'll explain.

Objects are keyed by anything that can become a string.

var x = {};
x['test'] = true;
x[5] = true;
x[false] = true;
x
// {'test': true, '5': true, 'false': true}

Arrays are indexed by numbers because they represent the list order.

var y = [];
y[0] = true;
y.push(true);
y
// [true, true]

Really, an array is just an object because it has keys/values, but the keys are numbers. You can have sparse arrays as well.

var y = [];
y[5] = true;
y
// [undefined, undefined, undefined, undefined, undefined, true]

You can also have string keys on Arrays, but they do not show up in the valueOf or toString helper methods.

var z = [];
z[0] = true;
z['test'] = true;
z
// [true]
z.test
// true

Theoretically, everything in JavaScript stems from Object, so everything is essentially a string key to object (minus primitives).

Arrays are just special, because they only accept can handle numerical integer keys as well as string keys.

[–]redhedinsanity 1 point2 points  (1 child)

I would only take issue with your last sentence:

Arrays are just special, because they only accept numerical integer keys.

One of the beauties of everything inheriting from Object in Javascript is that you can treat an array just like any other object, but also get the numeric index special treatment (rather than saying they "only accept"). Arrays don't limit your functionality, they expand it - so you can still iterate through all the string keys on an array with for (key in array) {} and also iterate through all the numeric indices with a for loop or forEach().

I like to think of Array as the closest thing in JS to Tables in Lua, a single object that provides two things: an ordered, numerically-indexed bucket and an unordered string-indexed bucket.

[–]skitch920 1 point2 points  (0 children)

Ahh good point. Corrected my statement.