Lchi Lchi - 23 days ago 7
CoffeeScript Question

Getting the last element of an array in CoffeeScript

Is there a quick (short, character wise) way to get the last element of an array (assuming the array is non-empty)?

I usually do:

last = array[array.length-1]
last = array[-1..][0]


If you're using a modern version of CoffeeScript, do not use this. Use the answer by dule instead.

If you don't mind modifying the array,

last = array.pop()

If you don't want the array modified,

last = array[..].pop()

That compiles to last = array.slice(0).pop(). I think it's pretty readable to people already exposed to CoffeeScript or Python slices. However, keep in mind that it will be much slower than last = array[array.length-1] for large arrays.

I wouldn't recommend last = array[-1..][0]. It's short, but I don't think its meaning is immediately obvious. It's all subjective, though.