nthLoading saved progress…

nth

nth is Lodash's element accessor: _.nth(array, n) returns the element at index n, and a negative n counts back from the end. It's the standalone-function cousin of array[n], with the negative-index support that bracket access lacks — and the base that head and last are built on.

Implement nth(arr, n), plus head(arr) and last(arr). nth returns the element at index n (default 0), resolving negatives from the end. head is the first element, last is the last — each a one-liner over nth.

Signature

function nth(arr, n = 0) { /* element at index n; negative counts from end */ }
function head(arr) { /* the first element */ }
function last(arr) { /* the last element */ }

Examples

nth(['a', 'b', 'c'], 1);  // 'b'
nth(['a', 'b', 'c'], -1); // 'c'  — last element
nth(['a', 'b', 'c']);     // 'a'  — n defaults to 0
head([10, 20, 30]); // 10
last([10, 20, 30]); // 30
head([]);           // undefined

Notes

  • Default n is 0 — calling nth(arr) returns the first element.
  • Negative n — counts from the end: -1 is the last element, -2 the second-to-last.
  • Out of range — returns undefined, never throws.
  • head and last derive from nthhead is nth(arr, 0), last is nth(arr, -1). Don't reimplement the index math in each.
  • Read-only — none of these mutate the array.
Loading editor…