Search code examples
javascriptarraysecmascript-5

Array.every returns false instead of type error


In practising various JavaScript code katas, I came across this problem:

Write a function isIntArray with the below signature

function isIntArray(arr) {
    return true;
}
  • returns true if every element in an array is an integer
  • returns true if array is empty.
  • returns false for every other input.

I had made my own solution to this, but one of the accepted solutions was the following:

function isIntArray(arr) {
  return Array.isArray(arr) && arr.every(function (x) { return Math.floor(x)=== x });
}

Now i understand how the Math.floor section works when determining if x is a decimal, but what i don't understand is how it doesn't fall over when it encounters something like:

var arr = [1,2,"asd",NaN,5];

I Tried reading through some guides on Math.floor and Array.prototype.every and i can't find anything that explains this. Surely if x was a string then Math.floor(x) === x should return a TypeError?


Solution

  • Surely if x was a string then Math.floor(x) === x should return a TypeError?

    Nope. Most mathematical functions and operations return NaN if one of the operand cannot be converted into number and then operated upon.

    So, it becomes Math.floor("asd") === "asd" is essentially

    NaN === "asd" // which is obviously false