When getting an element from an array by using the bracket syntax and giving an index value if I give an index that is below zero, or above or equal to the length of the array it will result in undefined. That is unless for some reason I set some negative index value for the array which I could, but that is another matter. With respect of the theme of this post when I get array elements this way I will not just get the corresponding element from the end of the array, and effect that might be desired in some situations.
That is if I think about an array being this thing like that of a circle, rather than an finite line. If I do think about it that way than I am going to be disappointed without some kind of helper method maybe. So to get to the point say I have a sime array of string elements, that is five elements in total.
If I get index zero with the bracket notation I get the first element, if I get index four with the bracket notation, no problem. However if I get index negative three I will not end up getting index element two, and if I get index five that will not swing around and get me the first element.
The lodash _.nth method can be used to supply this kind of functionality in line with thinking of an array as being like a circle rather than a line segment.
Any number value that is given outside the range of the array will just be converted to whatever the corresponding index would work out to.
I wrote a post on the nature of the modulo operator, and why it does not work the way that you might expect it to. So if you attempt to correct the given index value like this:
You are going to have a bad time. That would be a pretty sleek one liner if it worked, and it will work with positive values that go equal to or beyond the length of the array, but not with negative index values.
As such you would need to do something else.
Making a vanilla js alternative to _.nth just involves working out how to make a modulo operation that works a different way in which a positive, valid, in range value is always given.
These lodash methods are helpful, many even though many of them can be written quickly, it still saves time. I know that lodash is now one of those projects like jQuery where much of this is no longer needed, but even when a method like that comes along lodash still helps with backward compatibility with those older browsers people still use.