JavaScript allows us to use iterators for going over the properties of a specific object or for going over the elements of a specific array. The following code sample shows how simple it is to use iterators in JavaScript.

<!DOCTYPE html>
<html>
<head>
    <title>The Iterator Function</title>
</head>
<body>
    <script type="text/javascript">
        var student = { name: 'James', id: 234234123, average: 88.2 };
        var vec = [23,54,76,8,345,4];
        var ob1 = Iterator(vec);
        //iterating using the next function
        document.writeln("<br/>"+ob1.next());
        document.writeln("<br/>"+ob1.next());
        document.writeln("<br/>"+ob1.next());
        document.writeln("<br/>");
        //iterating using for..in loop
        var ob2 = Iterator(vec);
        for(var item in ob2)
        {
            document.writeln("<br/>"+item);
        }
    </script>
</body>
</html>

The following video clip goes over this code sample, shows its execution and explains each and every part of it.

When calling next() once reaching to the last key value pair the StopIteration exception will be thrown. The following code sample shows that.

<!DOCTYPE html>
<html>
<head>
    <title>StopIteration Exception Demo</title>
</head>
<body>
<script type="text/javascript">
    try
    {
        var student = { name: 'James', id: 234234123, average: 88.2 };
        var ob = Iterator(student);
        document.writeln("<br/>"+ob.next());
        document.writeln("<br/>"+ob.next());
        document.writeln("<br/>"+ob.next());
        document.writeln("<br/>"+ob.next());
        document.writeln("<br/><br/>worked fine!");
    }
    catch(ex)
    {
        document.writeln("<br/><br/>"+ex);
    }
</script>
</body>
</html>

The following video clip goes over this code sample, shows its execution and explains each and every part of it.

In order to iterate the keys only we should pass over the value true as a second argument to the Iterator function. The following code sample shows that.

<!DOCTYPE html>
<html>
<head>
    <title>Iterating The Keys</title>
</head>
<body>
<script type="text/javascript">
    var student = { name: 'James', id: 234234123, average: 88.2 };
    var ob = Iterator(student,true);
    document.writeln("<br/>"+ob.next());
    document.writeln("<br/>"+ob.next());
    document.writeln("<br/>"+ob.next());
</script>
</body>
</html>

The following video clip goes over this code sample, shows its execution and explains each and every part of it.

You can find more video clips, code samples and various other training material for learning JavaScript in my free online courses website at http://abelski.lifemichael.com.

Leave a Reply

Your email address will not be published. Required fields are marked *