Read about Associative Array here

We have been learning together JavaScript objects. We have seen various way to create JavaScript objects in this post

Now let us see how JavaScript object’s properties can be fetched. There are two ways it can be fetched

  1. Using dot and property name after dot.
  2. Using Square bracket and property name as string.

Let us suppose that you have Student object as follows,


var student =
 {
 name: "dj",
 grade: 10
 };

You can access properties like below,


var studentname = student.name;
 var studentgrade = student.grade;

There is a catch in this approach of fetching JavaScript property. Even though JavaScript is a loosely typed language you cannot create property at the run time.

Other way JavaScript object properties can be read using square bracket and putting property name as string.


var studentname = student["name"];
 var studentgrade = student["grade"];
 alert(studentname);

You see here is that JavaScript objects are like Associative Array. You can read there objects using square brackets and property name as string.

Let us discuss what is advantage of fetching property name with square bracket over dot?

  1. In Square bracket you provide property name as string. String is data type so can be manipulated at run time.
  2. With dot you provide property name as identifier. Since they are not a data type so cannot be manipulated at run time.

Assume scenario when you need to create property name at run time then JavaScript object as Associative Array is very useful.


for (i = 0; i < 10; i++) {
 student["marks" + i] = 100 * i;
 }

alert(student.marks8);

Let us assume a scenario that you need to create property name as array syntax. You can do that on JavaScript object by using their property as associative array

In this way you can work JavaScript object as Associative Array. And as we see they are very useful in creating properties at run time. They can be very useful in complex scenario. I hope you find this post useful. Thanks for reading.

Advertisements

One thought on “How JavaScript Objects are Associate Array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s