Home > DeveloperSection > Articles > JavaScript For-in Loop

JavaScript For-in Loop


JavaScript JavaScript 
Ratings:
0 Comment(s)
 2532  View(s)
Rate this:

JavaScript For-in Loop

Introduction:

I am going to explain you the functionality of for in loop, because for-in loop is a little more different from other loops.

In Java Script there is another loop which is known as For-in Loop. It is used to loop through properties of an object. There are various objects like Navigator objects and Window objects which I will be explaining later on. These objects contain various properties which can be easily accessed using. The example given below gives an idea about what is for-in loop and why it is used.

Syntax of for-in Loop:

for (variable in object)

{

         Code to be executed

}

Example:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

</head>

<body>

    <script type="text/javascript">

<!--

        var WinProperty;

        document.write("Window Object Properties Names<br /> ");

        for (WinProperty in window) {

            document.write(WinProperty);

            document.write("<br />");

        }

        document.write("Exiting from the loop!");

-->

    </script>

</body>

</html>

It list out various properties of Window object. In similar way we can list of other object properties.         In each iteration one property of an object is assigned in a variable WinProperty. Till all of the property is not accessed and assigned to the variable the for-in loop will continue executing and printing the property name on the screen.

                This loop differs from the for loop, that for loop does not work on objects

 Output:

java script for loop

Conclusion:

In this article I explained the concept of for-in loop and how it works, how it differs from for loop.


Don't want to miss updates? Please click the below button!

Follow MindStick