Getting neighbors of array elements in JavaScript

Let some array be given, for example:

let arr = [1, 2, 3, 4, 5];

Let's print the elements of this array to the screen using the ordinary for loop:

for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }

And now let's remake our code so that not the current elements are displayed, but the previous ones:

for (let i = 0; i < arr.length; i++) { console.log(arr[i - 1]); }

As you can see, to solve the problem, we simply subtract the number 1 from the counter, thereby obtaining the key of the previous element.

Here, however, lies the problem: at the very beginning of the loop, the counter value will be zero and we will try to get the array element with the key -1. There is no such element, of course, and as a result we get the value undefined.

In general, this is logical just geometrically: the very first element of the array does not have a previous one. In other words, there are 5 elements in our array, but only 4 of them have the previous element.

That is, the number of previous elements are always 1 less than the number of elements in the array. It is logical in this case that the loop should perform one less iteration. So just start the loop with 1 and not with 0 and the problem will be solved:

for (let i = 1; i < arr.length; i++) { console.log(arr[i - 1]); }

Just stupidly displaying the previous elements is a stupid operation. Let's do something more meaningful. For example, let's find the sum of the previous and current array elements and print it to the console:

let arr = [1, 2, 3, 4, 5]; for (let i = 1; i < arr.length; i++) { console.log(arr[i - 1] + arr[i]); }

Given an array of numbers. Iterate over it in a loop and in each iteration of the loop print the next element of the array.

Modify the previous task so that in each iteration of the loop, the sum of the current and the next element of the array is displayed.

Given an array of numbers. Loop through it and in each iteration of the loop print the previous two elements of the array.

Modify the previous task so that in each iteration of the loop, the sum of the two previous elements and the current element of the array is displayed.

Given an array of numbers. Loop through it and in each iteration of the loop print the sum of the previous, current and next elements of the array.

enru