Monday 27 August 2018

JavaScript: for in loop

for in loop is used to get all enumerable properties of object.

forin.html
<!DOCTYPE html>

<html>

<head>
    <title>for in loop Example</title>
</head>

<body>
    <script>
        var employee = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            age: 26,

            getDetails: function() {
                return "[firstName = " + firstName + ", lastName = " + lastName + "]";
            }

        }

        for (property in employee) {
            document.write(property + " : " + employee[property] + "<br />");
        }
    </script>
</body>

</html>

Open above page in browser, you can able to see following text. As you observe the output, for-in loop don’t display the built-in properties like toString, it is because built-in methods are not enumerable

firstName : Hari Krishna
lastName : Gurram
age : 26
getDetails : function (){ return "[firstName = " + firstName + ", lastName = " + lastName + "]"; }

Since arrays are also special kind of objects in JavaScript, you can traverse array using for-in loop.

forin.html
<!DOCTYPE html>

<html>

<head>
    <title>for in loop Example</title>
</head>

<body>
    <script>
        var arr = ["Hari Krishna", "Gurram", 26];

        for (index in arr) {
            document.write(index + " : " + arr[index] + "<br />");
        }
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

0 : Hari Krishna
1 : Gurram
2 : 26





Previous                                                 Next                                                 Home

No comments:

Post a Comment