What is the difference between an array and an object in Javascript

The difference between an array and an object in javascript

Let's create a simple object and a simple array, both being empty:

<script> var array_1 = []; var object_1 = {}; </script>

Wow, look at all those functions! This is what you see when you take a look under the hood.

methods of the array object and the prototypal object

We added two lines of code, and we get all those functions. That's because javascript does a lot of work for us in the background. Open your console like I showed here and enter console.dir(array_1); and console.dir(object_1); to view these two objects (an array is an object under the hood) in the inspector. If we don't open the __proto__ we get a shorter overview:

two simple objects - an array and an object

The brackets [] create an empty array, the brackets {} create an empty object.

What we see here is the fact that our simple empty array's heritage is __proto__: Array [] whose heritage in turn is __proto__: Object { … } to which 31 functions have been added. Let's call them array methods. These are:

constructor: function Array() copyWithin: function copyWithin() entries: function entries() every: function every() fill: function fill() filter: function filter() find: function find() findIndex: function findIndex() forEach: function forEach() includes: function includes() indexOf: function indexOf() join: function join() keys: function keys() lastIndexOf: function lastIndexOf() length map: function map() pop: function pop() push: function push() reduce: function reduce() reduceRight: function reduceRight() reverse: function reverse() shift: function shift() slice: function slice() some: function some() sort: function sort() splice: function splice() toLocaleString: function toLocaleString() toSource: function toSource() toString: function toString() unshift: function unshift() Symbol(Symbol.iterator): undefined Symbol(Symbol.unscopables): undefined

Note that you can use all these functions on an array. But not on an object which doesn't have __proto__: Array []. Let's take a look at the few methods from __proto__: Object { … } .

methods and properties in the object viewer of firefox - quite sparse

These are the methods from __proto__: Object { … }. Let's call them primitive object methods.

__defineGetter__: function __defineGetter__() __defineSetter__: function __defineSetter__() __lookupGetter__: function __lookupGetter__() __lookupSetter__: function __lookupSetter__() constructor: function Object() hasOwnProperty: function hasOwnProperty() isPrototypeOf: function isPrototypeOf() propertyIsEnumerable: function propertyIsEnumerable() toLocaleString: function toLocaleString() toSource: function toSource() toString: function toString() valueOf: function valueOf()

Since __proto__: Object { … } is part of __proto__: Array [] You can also use primitive object methods on your array. But because __proto__: Array [] is not part of __proto__: Object { … } you can't use the array methods of __proto__: Array [] on your primitive object (object_1). This amounts to the fact that an array is an object, but an object is not necessarily an array.

Now let's test if all this is actually true.

The properties of an array

Let's fill the array and create some content. We do this by entering a numeral integer key between the brackets and assigning a content (in our object we use some strings) to the array variables:

<script> array_1 [1] = "11.04.2018"; array_1 [2] = "Sehr geehrte Damen und Herren,"; array_1 [3] = "mit großem Interesse habe ich im Internet Ihre Anzeige gelesen, die mich sofort angesprochen hat, weil ich zurzeit auf der Suche nach einem Angebot für eine Reise bin. Ihre Anzeige beinhaltet ein Programm, das vielfältige Möglichkeiten bietet und für mich daher geeignet erscheint, zumal ich mich für Musik und Kunst sehr interessiere. Ich beabsichtige nach München zu reisen, weil in München bald das Oktoberfest stattfindet. Als Kind habe ich immer gehört, dass dieses Fest wunderschön und eines der größten in Deutschland ist. Außerdem habe ich ein paar Fragen zu der Hotelreservierung, zu dem Fest selbst, und zu den Kosten für eine Person. Im letztem Jahr bin ich nach Hamburg gefahren. Dort bin ich drei Nächte geblieben. Zuerst habe ich den Hauptbahnhof und den Stadtpark besucht. Beide sind sehr schön. Danach bin ich auf der Reeperbahn spazieren gegangen, wo es viele Restaurants und Geschäfte gibt. Am Ende habe ich den Aufenthalt im Hafen genossen.Ich glaube, dass es die beste Reise meines Lebens war. Nun bin ich sehr gespannt auf München und ob diese Stadt meine Erwartungen übertrifft. Es wäre sehr nett, wenn ich eine baldige Antwort bekäme."; array_1 [4] = "Mit freundlichen Grüßen"; array_1 [5] = "Zaid Al Taufiq"; var stringnumber = "6";//a string is defined array_1 [stringnumber] = "This is a letter in German.";//the string variable is interpreted as a number var number = 7;//a number is assigned to a variable array_1 [number] = "This is a letter from a pupil.";//the variable is used as key, key [7] </script>

The array has inherited some methods, let's try length, length is not a function. It is a variable that contains the number of elements in an array. We added 7 elements.

Does console.log(object_1.length) give 7 or 8 elements? What do you think? Open the console to find out. You will find a lonely integer number at the top.

<script> console.log(array_1.length); </script>

The console says 8. How is that? We added only 7. Let's now use Object.keys (), it gives all the keys that you use in an array. We used 7 keys. These are the numbers in brackets.

[1]
[2]
[3]
[4]
[5]
[6]
[7]

Open the console to see.

<script> console.log(Object.keys(array_1)); console.log("The number of elements is: " + array_1.length); </script> keys of an array printed by Object.keys()

But how can the lenght of the array be 8? This is because of a common human error to think that the machine starts counting with 1, like a human would. It is therefore important to keep in mind that the machine starts counting with 0. The property no. 8 (not key 8) has not been defined, it exists, though. It is the property under key [0]. It has no value or rather the value "undefined". So:

<script> array_1[0]==undefined //true (equals operator) array_1[0]===undefined //true (strict equals operator) </script>

Let's leave key 8 empty and define key 9 now.

<script> array_1 [9] = "The letter was written in february 2018."; </script>

How many elements will array_1.length show now? What do you say? 9 or 10. Key 8 is empty.

<script> console.log(Object.keys(array_1)); console.log("The number of elements is: " + array_1.length); console.log("keys: "+Object.keys(array_1)); </script>

Object.keys gives 8 keys, array1.length gives 10 elements. This shows that empty elements are counted too. In the viewer they are called <empty slot> Let's inspect the array:

<script> console.log (array_1) </script> images/images_array_11-4-2018/content-of-an-array-in-the-object-viewer-of-firefox-console

In the object viewer of the firefox console you can see very clearly that the array has two empty elements of 10 elements.

Let's see if we can turn the array into an object.

<script> array_1.like_an_object = "Is this an object property?"; </script>

Yes it works, adress the property through the dot notation:

<script> console.log (array_1.like_an_object); </script>

And we see:

object-property-on-array-with-dot-notation

Let's define some more:

<script> array_1.like_an_object1 = "These are additional properties"; array_1.like_an_object2 = "which do not belong"; array_1.like_an_object3 = "to the initial array."; array_1.like_an_object4 = "They can be addressed seperately"; array_1.like_an_object5 = "and they have names"; array_1.like_an_object6 = "which are strings."; </script>

And print it.

<script> console.log(Object.keys(array_1)); console.log("The number of elements is: " + array_1.length); console.log("keys: "+Object.keys(array_1)); </script>

This is interesting. Why do we first have such a neat list of keys saying the length is 15, then the length property of array_1 says it's only 10 elements and then we get a crammed list of keys?

Array-with-object-properties-length-16

It says "15" because now we see that the list of keys is in itself an array when displayed by console.log(Object.keys(array_1));. But console.log("keys: "+Object.keys(array_1)); has a "+" operator that converts the array into a string, which is why it is crammed like that. It says "15" not because we defined 15 keys (we defined 14 and started with 1), but because that's the length of the array keys (not the length of the array array_1). It says "10" because we have 10 integer keys making up the array in array_1. Note that the length property of array_1 automatically keeps track of the number of elements in the array, but it doesn't count the other elements we defined.

Let's convert the array too, into a string (a comma separated string).

<script> console.log("array_1: "+array_1); </script>

Looks like:

array-converted-to-text

What's that comma? It is the first empty key [0] separated by a comma. You can see another empty element (key [8]) below (,,).

Talking obout objects and object_1

Let's fill the object. To get a feeling for these objects and javascript handling arrays and objects, please open the console and compare the commands and the printed outcome in the console. This will help you understand.

<script> var hallo = "Hallo"; var nichts =""; // object_1[hallo]= "Welt";// same as object_1["Hallo"]= "Welt"; //object_1["Hallo"] === object_1[hallo] //true //object_1["Hallo"] === object_1.Hallo //true object_1[nichts]= ""; object_1["hello"]="hello world"; // console.log("-----Hallo Welt--------"); console.log(object_1[hallo]); console.log(object_1[nichts]); console.log(object_1[hallo]); console.log(object_1[hallo]); console.log(object_1["hello"]); //console.log(object_1[Hallo]); // will give "reference error" console.log("-------------"); console.log(object_1[nichts]); console.log(object_1[nichts]); console.log(object_1[nichts]); console.log(object_1[hallo]); console.log(object_1[""]); console.log(object_1[""]); console.log(object_1[""]); console.log(object_1["hello"]); </script>

We created some properties for object_1 but there seems to be no length property. That's because object_1 is not an array, so it doesn't have its methods. object_1.length is undefined.

<script> console.log("---- dot notation ---------"); console.log(object_1.Hallo); console.log(object_1.Hallo); console.log(object_1.Hallo); console.log(object_1.Hallo); console.log(object_1.hallo); console.log(object_1.hallo); console.log(object_1.hallo); console.log(object_1.hallo); console.log(object_1.hallo); </script> <script> console.log("---- has the object got a property length? ---------"); console.log(object_1.length); console.log(object_1.length); console.log(object_1.length); console.log(object_1.length); </script> objeckt-gedruckt-in-console-von-firefox.jpg

Upshot of printing to the console

Difference between array and object

The upshot is that the difference between an array and an object is not to be seen directly. The operator [] doesn't behave differently with objects and arrays. The dot operator is only for objects. The brackets operator accepts variables like hallo, the dot operator will accept hallo, but since the variable object_1.hallo has not been defined, it will print "undefined". Nevertheless both operators can be used on both array and function (object_1["Hallo"]===object_1[hallo] and object_1["Hallo"]===object_1.Hallo). The [] operator will accept variables ([hallo] for ["Hallo"]) and strings (simply ["Hallo"]). The dot operator will accept only strings because they are variable or property names (object_1.Hallo). The interpreter will not interpret hallo in object_1.hallo as a variable name, instead it will interpret hallo as a string property name of object_1, and because no one defined object_1.hallo or object_1["hallo"] (which is the same), it will give undefined when printed. With numbers it is different. You can define object_1 [1] = "hi" but not object_1[one] = "hi". You will get ReferenceError: one is not defined. For it to work you first have to declare var one = "1" or var one = 1 (or any other number for that matter) or var one = "hi_there" (or whatever string). Then it will be legal. Numbers are special in that they are the native array index.

What makes an array special?

It's the array methods and properties like length that make it special. If you give an array a numerical index, this property will do the housekeeping for you. It will always give you the number of elements in the array. You can treat it like an object and assign properties, but that's kind of being unthankful, when it's working so hard for you to keep track of everything and offering you so many other fine methods.