Tech Junkie Blog: JavaScript Objects Deep Dive : Flexibility of Array Notation

Monday, May 1, 2017

JavaScript Objects Deep Dive : Flexibility of Array Notation

In JavaScript there are two ways to access an object, first by dot notation like this

product.name

or with array notation

product["name"]

They both get the job done.   However with the array syntax [""] you access the object as if it's an array but instead of accessing it by numbers or index you access it by the property names.  That's because JavaScript objects are associative arrays.  They look like other objects in other languages such as C, C++, and Java.  However they behave very differently.

In other languages objects are defined in advance, their properties are methods are fixed.  To add a property or method to the object you have to change the class the object instance is created from.


JavaScript on the other hand is a loosely typed language.  What does that mean?  That means the JavaScript program can create properties in any object.   In EMCAScript 5 and above you can set the object's writable property to false, thus preventing anyone who else from modifying your object.  But that's beyond the scope of this blog.  Sorry I always wanted to say that!...lol

So what is the advantage of an array notation?  Let's say you have a scenario where you want to store the number of cookies a kid in kindergarten has.  With the array notation it's very easy to store that information.

Let's demonstrate this feature with code:

var kindergarten = new Object();

keepTrackOfCookies(kindergarten, "Mikey", 15);
keepTrackOfCookies(kindergarten, "Christine", 1);
keepTrackOfCookies(kindergarten, "David", 2);

function keepTrackOfCookies(kindergarten, kid, cookies) {
    kindergarten[kid] = cookies;
}

console.log("kindergarten object: ");
console.log(kindergarten);

Here is the output:






As you can see beside the fact that "Mikey" was very hungry, it's very easy to keep track of how many cookies each kids have in the kindergarten class with the array notation.


No comments:

Post a Comment