Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?
I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.
var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';
console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);
Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc...?
Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?
Arrays are objects.
However, unlike regular objects, arrays have certain special features.
Arrays have an additional object in their prototype chain - namely Array.prototype. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.com/#x15.4.4)
Arrays have a length property (which is live, ergo, it auto-updates) (Read here: http://es5.github.com/#x15.4.5.2)
Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.com/#x15.4.5.1). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like '1', '2', '3', etc.) then the special algorithm applies (it is defined on p. 123 in the spec)
Other than these 3 things, arrays are just like regular objects.
Read about arrays in the spec: http://es5.github.com/#x15.4
Objects are an unordered map from string keys to values, arrays are an ordered list of values (with integer keys). That's the main difference. They're both non-primitive, as they're composed of multiple values, which also implies pass-by-reference in JavaScript.
Arrays are also a kind of object, though, so you can attach extra properties to them, access their prototype and so on.
In your revised example, you're only taking advantage of the fact that an array is actually an object, i.e. you can set any property on them. You shouldn't do that. If you don't need an ordered list of values, use a plain object.
Strings can be either primitive or objects, depending on how they were declared.
var str = 'yes';
Gives you a primitive, while,
var str = new String('yes');
will give you a String object.
All arrays are the same (Whether or not they were defined with [] or new Array()), are of the type object and inherit from the "Array" object's prototype. There aren't real classes in Javascript, everything is an object, and there's a system defined object called Array. It has a property called 'prototype' (of type object), and when you use the new keyword on an object with a prototype property, it creates an instance with a reference to the contents of the prototype and stores it in your variable. So all arrays you've ever used in Javascript are objects and instances of Array's prototype property.
In any case, although arrays really are objects, they behave like arrays because of their useful properties and functions (Such as length, slice, push etc).
Another note, although I said there are no classes, when you do this:
console.log(Object.prototype.toString.call(your_object));
it will give you a string in the form [object Object]. But what's useful is that when you call it with an array, you get [object Array] same with functions which give [object Function] and a number of other system defined types, which assists in differentiating between normal objects and arrays (Since the typeof operator will always just return the string 'object').
Try this
var a = Array;
and go into firebug and examine the contents of a, especially it's 'prototype' property.
Edit: Changed the wording a bit, to be more correct. In fact when you use the new keyword, it creates an instance which references the prototype object. So any changes made to the prototype after the instance's declaration, will still affect the instance.
Edit: In answer to your latest revised question (are arrays/objects actually strings in disguise): No. They are objects, as I've explained. Strings are either a primitive type, or an object type (An instance of the String object) which contains the primitive equivalent as one of it's properties.
Arrays are not primitives in Javascript, they are objects. The key difference is that as a result, when you pass an array to a function it is passed by reference, not by value.
So yes! Arrays are objects in javascript, with a full blown Array.prototype and everything (don't touch that though...)
The confusion comes from the fact that javascripts lets you access object attributes in two ways:
myObj.attribute
or
myObj["attribute"]
Really what makes an array an array has nothing to do with the way you store data -- any object can store values using the syntax you use to store the array -- what makes an array an array is the fact that array methods (e.g. shift() and sort()) are defined for Array.prototype.
Trying to be brief with what I believe to be of the most significance: arrays have a number of methods that objects do not. Including:
length
push
pop
An object declared as var x = {foo:bar} has no access to a .length() method. They are both objects but with the array as a sort of superset with methods mentioned as above.
I don't feel I this is even close to being of Crockford standard in terms of explanation but I'm trying to be succinct.
If you want to get some quick results, open up Firebug or your javascript Console and try Array.prototype and Object.prototype to see some details
Update: In your example you declare an array and then do:
foo['bar'] = 'unexpectedbehaviour';
will produce unexpected results and won't be available in simple loops such as:
var foo=[0,1];
foo['bar'] = 2;
for(var i=0;i<foo.length;i++){
console.log(foo[i]);
}
//outputs:
//0
//1
An array can accept foo['bar']=x or foo.bar=y like an object but won't necessarily be available to be looped through as highlighted above.
Not that I'm saying that you can't iterate through the properties of an object, just that when working with an Array, you're utilising that unique functionality and should remember not to get confused.
In JavaScript you have a few types, everything else is an object. The types in JavaScript are: boolean, number, and string. There are also two special values, "null" and "undefined".
So the quest "is a JavaScript array an object?" is slightly ambiguous. Yes, a JavaScript array is an "object" but it is not an instance of "Object". A JavaScript array is an instance of "Array". Although, all objects inherit from Object; you can view the inheritance chain on the MDC. Additionally, arrays have slightly different properties than an object. Arrays have the .length property. They also have the .slice(), .join(), etc methods.
Douglas Crockford provides a nice survey of the language's features. His survey discusses the differences you are asking about. Additionally, you can read more about the difference between literals and constructors in question #4559207.
Arrays are Objects, but of a specialized nature. Objects are collections of values indexed by keys (in Javascript notation, {'key': 'value'}), whereas Arrays are Objects whose keys are numeric (with a few functions and properties). The key difference between them is obvious when you use a for each loop--an Object will iterate over all the values in its properties, whereas an Array will return the keys instead. Here's a link to a JSFiddle demonstrating the difference--notice that the first for each, which uses an array, returns the indexes, not the values; in contrast, the second for each returns the actual values at those keys.
When using the built-in methods available for arrays in Javascript, some methods will act directly on the calling array.
For example, myArray.sort(), will sort myArray in ascending order, alphabetically or numerically.
myArray.sort();
// sort() acts directly on myArray, changing it in its place thereafter
// ... also myArray.reverse() amongst others.
While other methods such as slice(), require there be something, either a variable or other output for it to return its value to...
var need_a_new_array = myArray.slice(10, 21);
// a new placeholder is needed for the results of slice... if not using
// the results immediately (i.e. passing to another function or
// outputting the results)
I was wondering what is the proper terminology for these methods and their differences. I am using arrays as an example here, but I'm sure that the
same probably holds true for objects in general.
I appreciate any help. Thank you.
The correct terms are mutator and accessor.
A mutator method mutates (changes) the object it is called on, while an accessor accesses (and returns) the value of the object it is called on.
You can see examples of the two types by looking at the method listing for Array.prototype. Note that they are divided into categories, two of which are Mutator methods ("These methods modify the array") and Accessor methods ("These methods do not modify the array and return some representation of the array.")
Mutators can not be called on immutable objects.
See also this related question on the software engineering SE: What is the term used to describe a function/method that modifies the object it's called on?
The terms you're looking for are 'immutable' and 'mutable' . Array.prototype.sort is a mutable method in that it 'mutates' (changes) the original array, where as Array.prototype.slice is immutable as it creates a new array with the result and leaves the original array intact.
I had an interview where the person asked me this question. Can anyone explains all the aspects so that i have a clear idea which structure to use when.
Arrays:
Arrays provide order, Object's don't (at least not yet).
Arrays can be optimized (speed and even the memory footprint), when used as non sparse lists with items of the same type.
Arrays provide a bunch of functions to work with this data-structure
Objects:
Objects are more generic
Using the Object as a Dictionary: lookups are faster than iterating over an Array to find the right item. return itemsById[id]
Code for Objects with the same hidden class can also be optimized.
Conclusion:
Arrays: use them if you think of the data as a list; same type improves performance but ain't a requirement.
To be more precise: lists have no gaps (missing indices), the data may have gaps, but the list shouldn't. If the list would have gaps, then the index has a meaning beyond just order, and it's probably a Dictionary with numeric keys.
Dictionaries: Plain Object used as a dictionary for the advantage of the fast lookup. Mentioned separate, because it's a different state of mind, having/dealing with a dictionary of items and dealing with an Object composing some properties.
Objects: A composition of properties of "some object". Like the body parts of a person. Or the "row" in a table of data: {id, firstName, lastName, ...}
Avoid enumerated properties. If you have sth. like {foo1, foo2, foo3, ...} foo is most likely a list of whatever, and should be built as such (just makes your life easier). unless this object is a dictionary
I've been following Backbone Collection's convention of having arrays of data objects and using _.find/findWhere etc to loop through the array, even when I wasn't using Backbone. However it seems like it would be more efficient to instead store them as an associative array with the id as keys if I know that they will be unique. Are there any pitfalls to this that I'm not seeing?
So basically:
var map = {};
map["someId"] = someObject;
map["someOtherId"] = someOtherObject;
// ...later to get the object:
var o = map["someId"];
If so, then the answer to "are there any pitfalls...I'm not seeing" is "no": Looking up properties on objects is a very common operation, which JavaScript engines do very quickly.
In fact, since normal JavaScript arrays aren't really arrays at all, it's markedly more efficient to look things up this way rather than storing them in arrays and using forEach or similar to find them. Every time you get an entry from an array (e.g., a[0] or whatever), that's a property access operation, just like looking up a property in an object. (In fact, that's exactly what it is, barring the JavaScript engine knowing it can optimize the operation.) Getting an element from one of the new typed arrays is faster because they really are arrays (although searching through them will still be non-trivial), but getting an element from a standard array is a property lookup on an object, so you might as well just do one lookup (on your map, using your key) instead.
(Side note: In JavaScript, the term "associative array" isn't usually used. It's just an object. Sometimes you also hear "map".)
I know that Javascript Arrays are actually objects, and because they are objects, they can have properties. Here's an example:
var a = [1, 2, 3];
a.currentIndex = 2;
a.next = function() { ... };
a.prev = function() { ... };
a.length // returns 3
To me this seems like it could come in very handy. I see numerous reasons why you might want to store state or utility functions on the actual array itself and not on some other variable. It even seems better than having the array as a property of an object with the other stuff stored on that object.
Here's my question:
Does anyone know of any issues with storing properties on a Javascript array? Does it work in all browsers? Is there any evidence that this will change with future versions of Javascript? Is there any general wisdom about whether or not it's a good practice?
(p.s. For the record, I don't need to iterate over the array with a for...in loop. I understand that such a loop would include the properties as well)
Since you already ruled out the for in issue, my answer here is a clear "no" - there is no issue to worry about. All Array.prototype methods will only apply on the "indexed" keys (0...n).
The best example here is the well know jQuery library, it also uses Array-Like objects to store DOM nodes on but it also has lots of methods which are attached to that object (jQuery uses the prototype there tho). However, other librarys like Zepto, just put those methods directly on the "array" object itself.
So again, no there is no other caveat and you're save doing it.
Just throwing out one more thing -- None of the "copying" array prototype functions will copy any of your extra properties, if that's important, i.e. .splice, .slice, concat will give you new "clean" arrays without currentIndex, etc
Yes it works in all browsers. And it is valid javascript (arrays are objects). One could think of a number of reasons why you want to use the Array constructor instead of an object, but if this is your preferred coding style, go with it.