Search code examples
javascriptarraysfindpolyfills

Why not trigger the TypeError when `this == null`


Array.prototype._find = function(callbackfn, thisArg) {
  if (this == null) {
    throw new TypeError('this is null or not defined')
  }
  if (typeof callbackfn !== 'function') {
    throw new TypeError('callbackfn is not a function')
  }

  for (let i in this) {
    if (callbackfn.call(thisArg, this[i], i, this)) return this[i]
  }

  return undefined
}

console.log(Array.prototype._find.call(null, x => x > 21))

This is a Array.prototype.find polyfill, what I except is trigger TypeError when run console.log(Array.prototype._find.call(null, x => x > 21)), I'm confusing why not trigger TypeError


Solution

  • You are probably running your function in "non-strict" mode. As per the documentation:

    function.call(thisArg, arg1, arg2, ...)

    thisArg

    Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.

    From the MDN page on Function.prototype.call, emphasis mine

    Here's an example. The first block runs in strict mode and will log null. The second one will log window, since that's the global scope for your browser. (Please give the stack snippet some time to log the window object, it's quite slow)

    (function() {
      "use strict";
      
      function logThis() { console.log("strict:", this); }
      
      logThis.call(null);
    
    }());
    
    (function() {
      
      function logThis() { console.log("non-strict:", this); }
      
      logThis.call(null);
    
    }());