Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Objects Deep Dive : Flexibility of Array Notation

Thursday, October 28, 2021

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.





3 comments:

  1. A firmware file is used to upgrade or install your operating system again on your device. This file is unique for every phone. If you are facing any issues like software issues and Boot loop issues, you can download this file to fix all the issues.Infocus m430 how to flash

    ReplyDelete
  2. Loved the content! You have covered all aspects of the subject in this article, Thanks a lot.
    Artificial Intelligence Training in Hyderabad
    Artificial Intelligence Course in Hyderabad

    ReplyDelete
  3. We establish strong internal security culture to provide convenience so that your devices can identify and respond to threats.

    ReplyDelete

Search This Blog