Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Array Deep Dive : Iterating Through Array

Thursday, November 25, 2021

JavaScript Array Deep Dive : Iterating Through Array

Since an array is a collection of elements of objects, values, etc.  The most common function performed on it is to iterate through each elements of the array.  The most frequent way to do that is with a for loop.

Let's say you have an array with the following:

var numbers = ["one","two","three","four","five"];

The numbers array above contains five string elements, which also has a indexes associated with the it.  There's also a length that is defined with each array that we will use for the for loop we are about to write.  So what do the you length of the numbers array will be?

If we output the array to the browser with the statement console.log(numbers.length) do you think we will get the length to be 5 or 4?

If you guess 5 you are correct because there are five elements in the array.  However, the arrays have zero based indexes therefore the index is always length -1

for(var i = 0; i < numbers.length; i++)
{
     console.log(numbers[i]);
}



The loop above loops through the array by comparing the value of i to the length of the numbers array.  It simply use the value of i as the index in the body of the loop.  So the loop above will produce the following output:


Notice we use the operand i < numbers.length instead of i <= numbers.length because if we try to access an element with the fifth index we will get an undefined.  That's the good and bad thing about JavaScript it does not crash your program, however it let's you get away with a lot of things.




So if you type the following

        for (var i = 0; i <= numbers.length; i++) {

            console.log(numbers[i]);

        }


You will get the same result except the fifth index will be undefined.

But another scenario is that some developer decides to delete an element of the array with the delete keyword, leaving the array with an empty element or undefined.  How would you handle that situation?  First let's create the situation where that could happen.  By the arrays with empty elements are called sparse arrays or loose arrays.  Tight arrays are arrays with all the elements defined.

So let's create a sparse array with the delete keyword.

delete numbers[2];

If you output the numbers array now you will see that the element with index 2 is now missing or undefined.  If you use the for loop again to output the browser you will see the following

        for (var i = 0; i < numbers.length; i++) {

            console.log(numbers[i]);

        }

As you can see the element with index 2 is undefined which happens to be the string "three"

Now let's say you want to output only elements that are defined, what do you do?

Well there are two ways to do that, the first is to check to see if the element is "undefined" then skip the element the "continue" keyword to go to the next iteration.

You would write the loop like this:


        for (var i = 0; i < numbers.length; i++) {











       
            if(numbers[i] == undefined)
                   continue;
            else
               console.log(numbers[i]);

        }

The loop above skips the current iteration of the for loop if an undefined is found, but writes out the value of the element if it has a valid value.

Another method is to check to see if the element is exists at all, which also checks for null values.  To check to see if the element exists with a valid value you can put a ! in front of the current element.





Like the code below:

        for (var i = 0; i < numbers.length; i++) {

            if (!numbers[i])
                continue;

            else
                console.log(numbers[i]);
        }

It will give you the same result as the undefined check, but this one will also weed out the elements that assigned null values.

You can also use the for/in loop for sparse arrays.  It will automatically check for elements with valid values and only deals with those.

For instance you can write the loop as

        for (var i in numbers) {

                console.log(numbers[i]);
        }

And it will same output, so it's up to you which method you want o use.











No comments:

Post a Comment

Search This Blog