Go To Content
codylindley.com

codylindley.com

JavaScript Tidbits - Array Objects Are Object Objects and Object Objects Are Associate Arrays

Arrays and objects are both a collection of data values (string, number, boolean, or object). Consider the following code that creates two objects. And remember, an empty array and empty object are both objects. That is why we refer to them as "array object" and "object object".

var myArrayObject = ["a", "b", "c"] 
// collection of strings created using an array literal, which creates an array object
var myObjectObject = {a:"first letter of alphabet", b:"second letter of alphabet", "c":"third letter of alphabet"}
// collection of strings created using an object literal, which creates an object object

Array objects treat the collection as ordered values. Meaning that each value (often called an element) in an array collection is giving a numeric index starting with 0. So the following code will reference the value of the third element in the myArrayObject array.

alert(myArrayObject[2]); //alerts "c"

Object objects treat the collection as unordered named values. Meaning that each value (often called a property) in an object is given a name. The name can be an identifier or string. So the following code will reference the value of the property named c, in the myObjectObject object. It should be noted that c is a string.

alert(myObjectObject.c); //alerts "third letter of alphabet"

Now if your javascript kung fu is top notch then you also know that you could obtain the property value of c using a string instead of an identifier. Like so:

alert(myObjectObject["c"]); //alerts "third letter of alphabet"

Accessing the value of c like we just did is often called an associate array. Which seems silly. Because an associate array is really an object object and not an array object. But then again an array is really just a special kind of object object.

 
  1.   #1 Comment Posted by Nathan Smith on Jun 5, 01:00 PM

    Code-dawg: I’m curious as to why, in your second code example, a and b are not in quotes, but c is. Was this intentional?

  2.   #2 Author Comment on Jun 5, 03:11 PM

    Yes, its to show that object properties can be an identifier (like a variable name) or a string. Also we can access object properties using an identifier or a string. I was trying to show the relationship there.

  3.   #3 Comment Posted by Nathan Smith on Jun 5, 03:59 PM

    Ah, ok. I figured it wasn’t a typo. I was more just wondering what the magic was. Thanks for pointing it out to my feeble brain.