Jaa


For In Loop in JScript

Hi,

It's been more than one year since my last post. I will try to be regular now on :).

BTW, during this period, I have moved to Jscript team and will be sharing my little knowledge on JScript with you all.

Recently I investigated a bug wherein user complained that for... In loop in JScript doesn't work. It doesn't enumerate through members of an array like the for..each loop of VBScript or C#. Since I am also new to Jscript and was not sure of the for...in behavior I decided to debug the code and here are the results...

JScript For in loop is different from for-each of VBScript or C#. For each loop of VBScript and C# indeed iterates through the members of an object but Jscript for in loop actually iterates through indexes. What does that mean? Iterating through indexes not members? Well, let's work out an example...

var arr = new Array(10, 20, 30);

for (oBinding in arr)

{

WScript.Echo(oBinding)

}

What do you think should be the output of above code snippet? Shouldn't it be 10, 20, 30?

If you run above code, then output will be 0, 1, 2, which are actually array indices. If you want to print the members then you need to change above code as following...

var arr = new Array(10, 20, 30);

for (oBinding in arr)

{

WScript.Echo(arr[ oBinding ] )

}

Above code snippet prints what you were expecting, 10, 20, 30. Hmmmm.... then why do i need a for..in loop at all. I can just use a for loop to print the array members like following....

for (count = 0; count < arr.length; count++)
WScript.Echo(arr[count]);

Correct! But the need of for..in loop arises when you have a sparse array. JScript arrays are sparse arrays, that is, although you can allocate an array with many elements, only the elements that actually contain data exist. This reduces the amount of memory used by the array. Consider following example...

var arr = new Array();
arr[10] = 2;
arr[15] = 4;
arr[20] = 5;

for (oBinding in arr)
{

           WScript.Echo(arr[oBinding])

}

In above code array arr has only 3 valid elements though it's size is 20. If you use a for loop to access this array, you will be accessing all 20 elements which is unnecessay waste of CPU time. Instead if you use for...in loop you will just access 3 elements. Huge saving of CPU!!!

In other words what you can say is that for..in allows you to randomly access the array.

Same holds true for object properties also. What if you have a Jscript object but you don't know what all properties it holds. Answer is the for…in loop. Just use a for..in loop on that object and get hold of all the properties. Simple!