Part 9 and 10 of 256: Array#first and Array#last
The first and last methods of array objects provide a nice semantic wrapper for the concepts. They aren’t really a big time saver, though it is probably very slightly easier to type first than [0]. It is also fairly uncommon to need these methods with much regularity, but when you do need them it’s nice to have them.
/**
* Returns the first element of the array, undefined if the array is empty.
*
* @returns The first element, or undefined if the array is empty.
* @type Object
*/
Array.prototype.first = function() {
return this[0];
};
/**
* Returns the last element of the array, undefined if the array is empty.
*
* @returns The last element, or undefined if the array is empty.
* @type Object
*/
Array.prototype.last = function() {
return this[this.length - 1];
};
