Function that checks if array only contains elements of a specific type The function checks whether an array is of a specific type (only contains elements of that type), the types the function accepts for checking is basically all the JavaScript types plus any types that the user may define manually (using a constructor).

What would you do to make the function more sophisticated? What would you remove or add? How would you improve or extend the function? 



const checkArrayType = function checkArrayType(arr, type) {
  
  if (!Array.isArray(arr)) {
    throw new Error('The argument "arr" must be an array!');
  }
  else if (type !== null &amp;&amp; type !== undefined &amp;&amp; typeof type != 'function') {
    throw new Error('The argument "type" must be a function, "null", or "undefined"!');
  }
  
  // 'null' and 'undefined' require a different check than the main one
  if (type === null || type === undefined) {
    return arr.every(function(e){
      return e === type;
    });
  }
  
  return arr.every(function(e){
    /* 
     * not using 'instanceof' because it would return 'true'
     * for cases like 'subObj instanceof Object'. 
     * ---------------------------------
     * using 'Object(e)' so that the check works for primitives, see:
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
     */
    return Object.getPrototypeOf(Object(e)) === type.prototype;
  });
  
};


console.log(checkArrayType([1,2,3,4], Number)); // true
console.log(checkArrayType(['hello', 10], String)); // false
console.log(checkArrayType([[1, 2.5], ['a', 'b']], Array)); // true
console.log(checkArrayType([null, null, null, null], null)); // true
console.log(checkArrayType([new String('hello'), new String('world')], Object)); // false

var Foo = function Foo(){};
console.log(checkArrayType([new Foo(), new Foo()], Foo)); // true

console.log(checkArrayType({a: null}, null)); // throws error
console.log(checkArrayType([], 'abc')); // throws error




One more thing, how am I supposed to deal with long comments like the one in this snippet ?
The implementation could be written more compactly using arrow functions, for example:

if (type === null || type === undefined) {
  return arr.every(e =&gt; e === type);
}

return arr.every(e =&gt; Object.getPrototypeOf(Object(e)) === type.prototype);


There are two arr.every calls at different execution paths.
You could eliminate that duplicated logic by extracting the function parameter of arr.every to a variable:

var checker;
if (type === null || type === undefined) {
  checker = e =&gt; e === type;
} else {
  checker = e =&gt; Object.getPrototypeOf(Object(e)) === type.prototype;
}

return arr.every(checker);