DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Infinitely loop over an array

const loopOverArray = (arr) => {
  let index = -1;

  const getNextElementFromArray = () => {
    index++;
    const nextIndex = index % arr.length;
    return arr[nextIndex];
  };

  return getNextElementFromArray;
};

const getNextElement = loopOverArray([1, 2, 3]);

console.log(getNextElement()); // 1
console.log(getNextElement()); // 2
console.log(getNextElement()); // 3
console.log(getNextElement()); // 1
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Latest comments (0)