Tuesday, March 8, 2016

Caution JavaScript Ahead - Is length good to loop arrays?

This is not to prove one particular method as the best method. But just to understand different behaviors. It can be considered as an extension to below post about same.

http://joymonscode.blogspot.com/2015/08/multiple-ways-to-iterate-array-in.html

Looping using array.length

Look at the below code

var arr = [];

function addElementTo100thPosition() {
    arr[100] = "Hundred"
    console.log("Added element to 100th position. Length of array:" + arr.length);
}
function printArrayByLoopingLength() {
    for (var i = 0; i < arr.length; i++) {
        console.log("Element at " + i + " is "+ arr[i]);
    }
}

What it will display if the printArrayByLoopingLength() is called after addElementTo100thPosition() is executed? First of all, will there be any error if we directly add element to 100th position?

There won't be any confusion on adding item to 100th position directly. Its possible. If that is possible we should be able to iterate till that element. So it should iterate 100 times. For that length must be 100. Yes all is right. The output will be like below

Element at 0 is undefined
Element at 1 is undefined
Element at 2 is undefined
Element at 3 is undefined
Element at 4 is undefined
Element at 5 is undefined
Element at 6 is undefined
.....
Element at 100 is Hundred


This is because the length means the highest integer index + 1. Not the number of elements. of.If we display the array via JSON it will look as follows everything converted to null.

function printArray(){
    console.log(JSON.stringify(arr,null,2));
}
[ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "Hundred" ]

Is this a good behavior? We can say it depends. If we have an algorithm which fills data into an array randomly, we can use it. But if we think of iterating the elements, this is not the right way. Lets see another way in next post.

Here lets see one more scenario.

Adding elements to array with non integer index

What it one element is indexed with string not like numbered.

function addElementWithStringIndex(){
    arr["name"] = "Joy"
    console.log("Added element to 10th position. Length of array:" + arr.length);
}

If we call the printArrayByLoopingLength() after calling the above function, what we will get.

It will be same as above. Try to call printArray() which uses JSON.stringify(). Its still the same output. It don't get the element indexed with string key.

What happened to the element "Joy" we added to the array. Lets display using arr.name

function printArrOfName(){
    console.log("arr['name'] is " +arr["name"]);
}

It displays the value.
arr['name'] is Joy

What does it mean. The string indexed element became a property. Try the below

function printArrDotName(){
    console.log("arr.name = " +arr.name);
}

The output will be

arr.name = Joy

Array.push

One more scenario. What will happen if we using push() method instead of directly putting into the array?

function pushToArray(){
    arr.push("Pushed element");
}

Now call the methods in below order
  • addElementTo100thPosition
  • pushToArray()
  • printArrayByLoopingLength
The output will be
Added element to 10oth position. Length of array:101 Element at 0 is undefined Element at 1 is undefined Element at 2 is undefined Element at 3 is undefined Element at 4 is undefined Element at 5 is undefined ... ... Element at 100 is Hundred Element at 101 is Pushed element

push insert the element to the end of the array. It looks for length and insert after that. It uses integer index. Even if we call printArray() the JSON string will be correct with the pushed element.

Moral of the story

  • Do not index using string if its really going to be an array. Use integer to index array.
  • Use push to insert into array.
  • Do not iterate using length because it depends on last element's index not real no of elements.
What the best practice? Lets see in coming posts.

No comments: