Why can I add named properties to an array as if it were an object?

Viewed 69968

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?

8 Answers

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.

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 

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.

In JavaScript Arrays are special typed objects

typeof new Array(); // returns "object" 
typeof new Object(); // returns "object

Arrays used numbered Indexes and Objects used named Indexes

so we can able add named properties to Array

const arr = []
arr["A"] = "Hello" //["A":"Hello"]

console.log(arr.length) // 0 

arr.length returns 0 , because array with named indexes are prefer to call Objects

console.log(Object.keys(arr)); // ["A"]
console.log(Object.keys(arr).length); //1

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>");
Related