Rory Perro
Rory Perro

Reputation: 451

underscore last from scratch

This is a way to write out underscore _.last() from scratch. _.last returns the last element of an array. Passing n will return the last n elements of the array.

Please help me understand this code. What does the -n mean as a parameter of array.slice? Shouldn't it just be n, since, by definition, we'd be passing in the last n elements of the array? So why -n?

_.last = function(array, n) {
  if (n === 0) { 
    return [];
  }
  return n === undefined ? array[array.length -1] : array.slice(-n)

Upvotes: 0

Views: 467

Answers (1)

Alex Booker
Alex Booker

Reputation: 10777

From the .slice documentation:

As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

Passing n to .last is supposed to return the last n elements of the array.

As per the documentation, passing -n to .slice returns the last n elements of the array.

Upvotes: 4

Related Questions