This post will discuss how to iterate from the second element of an array in JavaScript.

To iterate from the second element of an array in JavaScript, we can use one of the following functions:

1. Using for loop

A for loop is a common way to iterate over an array in JavaScript. We can use it to iterate over the array from the second element to the last element, and then do something with each element at the current index. The index starts from 1 instead of 0 to skip the first element. For example, we can initialize the index variable to 1 and use it to access the array elements as follows:

Download  Run Code

2. Using forEach() function

The forEach() function is a built-in function that executes a callback function for each element of the array. To iterate from the second element of an array using the forEach() function, we can use the index parameter to check if it is greater than or equal to 1 and skip the first element. The index is passed as a second argument to the callback function. For example:

Download  Run Code

 
With ES6, we can use an arrow function (=>) as the callback for the forEach() function and the spread operator (…) to call forEach() on slice of the original array. We can use slice() function to create a new array without the first element by passing a start index of one. For example:

Download  Run Code

3. Using for…of loop

A for…of loop is a new way to iterate over iterable objects like arrays in JavaScript. It takes a variable that represents the value of each element and assigns it in each iteration. However, the for…of loop does not provide access to the index or the array, but it can be combined with other functions or operators to achieve that. To iterate from the second element of an array using a for…of loop, we can use the Array.entries() function to get an iterator that returns [index, value] pairs for each element and use array destructuring to assign them to separate variables. Then we can check the index of each element and skip the first pair. For example:

Download  Run Code

That’s all about iterating from the second element of an array in JavaScript.