Nodejs Array First Predicate first(fn)

Here you can find the source of first(fn)

Method Source Code

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

Array.prototype.first = function(fn) {

    // 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);
    }//from   w w  w .j a  v  a 2 s.c o  m

    // No predicate? Return first element

    if (typeof fn === 'undefined') {
        return this[0];
    }

    // Return first element that meets predicate

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

    for (var i = 0, l = this.length; i < l; i++) {
        var element = this[i];
        if (fn.call(this, element, i, this)) {
            return element;
        }
    }
};

Related

  1. first(f)
    Array.prototype.first = function(f){
        var i = 0;
        while(i < this.length){
            if(f == undefined){
                return this[i];
            if(f(this[i])){
               return this[i];
            i++;
        return null;
    };
    
  2. first(func)
    Array.prototype.first = function(func) {
      return this.where(func)[0];
    };
    
  3. first(func)
    Array.prototype.first = function(func) {
        var result = [];
        for(var i=0;i<this.length;i++) 
            if (func(this[i]))
                return this[i];
        return null;
    
  4. first(func)
    Array.prototype.first = function (func) {
        var length = this.length,
            item = null;
        for (var i = 0; i < length; i++) {
            if (func(this[i])) {
                return this[i];
        return item;
    ...
    
  5. first(matching)
    Array.prototype.first = function(matching) {
        for (var i = 0; i < this.length; i++) {
      var entry = this[i];
      if (matching(entry) == true)
          return this[i];
        return null;