Custom Iterator In JavaScript

Introduction

 
In computer programming, an iterator is an object that enables a programmer to traverse a container, mainly an Array or list of items.
 
In JavaScript (ES2015 onwards) Symbol.iterator is there to convert an array into iterable, which was not present in older versions of JavaScript.
 
Let's discuss how to create a custom iterator using JavaScript (ES5).
 
Description
 
Let's first create a function which will convert the input array into an iterable. 
  1. function iterator(array) {  
  2.     var currentIndex = -1;  
  3.     return {  
  4.         next: function() {  
  5.             currentIndex = currentIndex + 1;  
  6.             return currentIndex < array.length ? {  
  7.                 value: array[currentIndex],  
  8.                 done: false  
  9.             } : {  
  10.                 value: "index out of range",  
  11.                 done: true  
  12.             };  
  13.         },  
  14.         previous: function() {  
  15.             currentIndex = currentIndex - 1;  
  16.             return currentIndex >= 0 ? {  
  17.                 value: array[currentIndex],  
  18.                 done: false  
  19.             } : {  
  20.                 value: "index out of range",  
  21.                 done: true  
  22.             };  
  23.         }  
  24.     };  
The above function is having 2 inner functions - next and previous. These functions ensure that we can move forward and backward in an iterable from its current position. These functions return the Value and Done.
  • Value represents the next or previous value in the array.
  • Done represents the status, whether the iteration is complete or not. 
Let's see an example.
 
I have created an array and assigned some values to it. 
  1. var a = [];  
  2. a[0] = 1;  
  3. a[1] = 2;  
  4. a[2] = 3;  
  5. a[3] = 4;  
Let's make it iterable.
  1. var iterable = iterator(a);  
  2. var current = iterable.next();  
  3. while (!current.done) {  
  4.     console.log(current.value);  
  5.     current = iterable.next();  
Output
 
1
2
3
4
 
Let's go back and forth in the array now.
  1. var res = iterator(a);  
  2. console.log(res);  
  3. console.log(res.next().value);  
  4. console.log(res.next().value);  
  5. console.log(res.next().value);  
  6. console.log(res.previous().value);  
  7. console.log(res.previous().value);  
  8. console.log(res.previous().value);  
Output
 
1
2
3
2
1
 
index out of range
 
Please try the above example here.
 
Please let me know your feedback and comments.