Nodejs Array Last last(fn, scope)

Here you can find the source of last(fn, scope)

Method Source Code

// Returns last element in array, or last element that matches a predicate fn

Array.prototype.last = function(fn, scope) {

    // Prototypes throw TypeErrors when the context or arguments are invalid

    if (Object.prototype.toString.call(this) !== '[object Array]') {
        throw new TypeError("`this` must be Array, not " + typeof this);
    }//w w  w  . j a  v a 2 s . com

    // No predicate? Return last element

    if (typeof fn === 'undefined') {
        return this[this.length - 1];
    }

    // Return last element that meets predicate

    if (typeof fn !== 'function') {
        throw new TypeError("Optional argument[0] must be predicate function if defined");
    }

    for (var i = this.length - 1; i >= 0; i--) {
        var element = this[i];
        if (fn.call(scope || this, element, i, this)) {
            return element;
        }
    }
};

Related

  1. last()
    Array.prototype.last = function() {
      return this[this.length-1];
    
  2. last()
    Array.prototype.last = function ()
      return this[ (this.length-1) ];
    };
    
  3. last()
    Array.prototype.last = function() {
        if (this.isEmpty()) {
            return null;
        return this[this.length - 1];
    };
    
  4. last()
    Array.prototype.last = function() {
        if (this.length == 0) return null
        return this.slice(this.length - 1)[0]
    
  5. last(arr)
    Array.prototype.last = function (arr) {
      return this[this.length-1]
    
  6. last(func)
    Array.prototype.last = function (func) {
        var length = this.length - 1,
            item = null;
        for (var i = length; i >= 0; i--) {
            if (func(this[i])) {
                item = this[i];
                break;
        return item;
    
  7. last(n)
    Array.prototype.last = function (n) {
        'use strict';
        return this.slice(this.length - (n || 1), this.length);
    };
    
  8. last(n)
    Array.prototype.last = function(n) {
      if (this.length == 0 || n < 0) return void 0;
      if (n == undefined) return this[this.length - 1];
      if (n == 0) return [];
      return this.rest(this.length - n);
    };
    
  9. last(num)
    Array.prototype.last = function (num) {
       if (num !== undefined) {
          return this.slice(-num);
       return this[this.length - 1];
    };