How to Create a Negative Index in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a negative index by simply using a negative number as the index to access elements in an array. For example:

let arr = [10, 20, 30, 40, 50];

console.log(arr[-1]);  // Output: 50
console.log(arr[-2]);  // Output: 40

Note that negative indices are relative to the end of the array, so arr[-1] returns the last element in the array (50), arr[-2] returns the second to last element (40), and so on.

Keep in mind that when using a negative index to access elements in an array, if the absolute value of the index is greater than the length of the array, it will return undefined.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply