Smart javascript arrays

September 16th, 2008   Filed Under Good to know, Javascript, Tips & Tricks, gyan, snippet, vivek  

Today I want to show you some really professional and efficient way to populate your javascript array.

When you declare an array you can do it simply by writing a short hand like:

var arrSalaries = [];

Notice that the square brackets[] itself delcares the array and you don’t have to write “new Array()”. So you save some characters like that. Thanks to javascript.

Sometimes you need to populate an array in a loop and generally people populate it like this:

for(i=0; i<something.length; i++)
{
  arrSalaries[i] = something[i].amount;
}

There is nothing wrong in the code but a more robust way would be:

for(i=0; i<something.length; i++)
{
  arrSalaries[arrSalaries.length] = something[i].amount;
}

This ensures that any exceptions(if any), would be taken care and the array would be properly populated. To be in simple words, let us say you have an exceptional continue statement in the for loop and the statement is executed on some event. In such a case, the array would be populated wrongly in the following fashion:

arrSalaries[0] = 200;
arrSalaries[1] = 200;
arrSalaries[3] = 200;// just now there was the exception
arrSalaries[4] = 200;
arrSalaries[6] = 200;// just now there was the exception

If you use the second method to populate the array you can avoid this problem.

Another thing in array(not everyone remembers) is the literal arrays.
So you can delcare an array with a literal like this:

var arrSalaries = [];
arrSalaries["vivek"] = 5000;
arrSalaries["shon"] = 5000;

And you can access them with a dot operator like:

alert(arrSalaries.vivek);

or the same way you declared it:

alert(arrSalaries["vivek"]);

One should always think to minimize the code as far as possible. Even a single character shows your optimization attitude.

Now after knowing this one obvious question comes to your mind that how to loop through this literal arrays:

The answer is the following code:

for(props in arrSalaries) //in case you have forgotten for ... in in javascript this is a reminder
{
    alert(arrSalaries[props]);//props represent the literal
}

The above way can be implemented to dig out any built-in or custom object to scan their attributes and methods.

But as commented by Andrew Dupont in his article associative arrays should not be used for storing values with literals at all.

Andrew is technically correct in saying that because you loose all the basic methods in this kind of array.

Better use  it like this:

var arrSalaries = {};
arrSalaries["vivek"] = 5000;
arrSalaries["shon"] = 5000;

So, what you replace is [] with {}. And hence, you come to know that {} is a shortcut of declaring an object. Enjoy madi !!


Comments

Leave a Reply