DEV Community

Cover image for Loop an array using closures in JavaScript
Jatin Panjwani
Jatin Panjwani

Posted on

Loop an array using closures in JavaScript

What if someone asks you to visit each element in an array without using any looping mechanism in JavaScript, what would you do?
.
.
.
.
.
.
Here comes closure to the rescue. While reading about this concept, I came across this problem and found it interesting.

Solution:

function getArrayItems(array){
 let i = 0;
 return function(){
   return array[i++];
 }
}


//print an array using concept of closure
const next = getArrayItems([1,2,3,4,5,6,7]);

function loop (cb) {
  const value = cb();
   if (value === undefined) {
     return;
   } 
   console.log(value);
   return loop(cb);
}

loop(next);
Enter fullscreen mode Exit fullscreen mode

Run code here : https://repl.it/@jatin33/ClosureExample#index.js
Please comment what are some other applications you guys can think of.

Top comments (0)