views:

479

answers:

4

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

and

var myObject = {'A': 'Athens', 'B':'Berlin'};

because they both behave the same, and also typeof(myArray) == typeof(myObjects) (both yield 'object').

Is there any difference between these variants?

A: 

The {}-notation is just syntactical sugar to make the code nicer ;-)

JavaScript has many similar constructs like the construction of functions, where function() is just a synonym for

var Func = new Function("<params>", "<code>");
Dario
+2  A: 

In JS arrays are objects, just slightly modified (with a few more functions).

Functions like:

concat
every   
filer
forEach
join
indexOf
lastIndexOf
map
pop
push
reverse
shift
slice
some
sort
splice
toSource
toString
unshift
valueOf
Casey
Although I don't think all of the functions listed are built-in every JS implementation, you got the point. The other difference would be different prototype (which is implied by those extra functions).
Rashack
+7  A: 

Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.

Here's a more concrete example why non-numeric keys don't "fit" an Array:

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

alert(myArray.length);

This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.

Paul Dixon
myArray.length returns a numeric index/key of the last element in array but not the actual number of elements. Are properties of the Array object not the same as array values?
dasha salo
I was just trying to illustrate the intended semantics of the Array object are abused if you just treat it like a regular object. The linked article does a better job though :)
Paul Dixon
A: 

Everything in Javascript is an object besides primitive types.

The code

var myArray = Array();

creates an instance of the Array object while

var myObject = {'A': 'Athens', 'B':'Berlin'};

creates an instance of Object object.

Try the following code

alert(myArray.constructor)
alert(myObject.constructor)

So you will see the difference is in the type of object constructor.

The instance of the Array object will contain all the properties and methods of the Array prototype.

dasha salo