DEV Community

loading...

Infinitely loop over an array

Mehul Lakhanpal
Full stack Developer | Micro-blogging on Web Development at codedrops.tech | Creator of File Ops, Note Box, GitHub Marker
Originally published at codedrops.tech ・1 min read
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.

Instagram ● Twitter ● Facebook

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

Discussion (0)