forward and reverse loop one by one js

Solutions on MaxInterview for forward and reverse loop one by one js by the best coders in the world

showing results for - "forward and reverse loop one by one js"
Zander
05 Jan 2020
1var arr = ['red', 'blue', 'black', 'green'];
2var currentIndex = 0;
3
4var nextBtn = document.getElementById('nextBtn');
5var prevBtn = document.getElementById('prevBtn');
6
7nextBtn.addEventListener('click', nextItem);
8
9prevBtn.addEventListener('click', prevItem);
10
11function nextItem() {
12  if (currentIndex === (arr.length - 1)) {
13    return;
14  }
15  
16  console.log(
17    arr[++currentIndex]
18  );
19}
20
21function prevItem() {
22  if (currentIndex === 0) {
23    return;
24  }
25  
26  console.log(
27    arr[--currentIndex]
28  );
29}