Array is acting like both a number and an array

Tell us what’s happening:

Could someone explain how the array at index 1 in the array below is somehow acting like a number and yet described as a object when I use typeof? I don’t understand why [2] is making it past the filters. See the console.log comments below to see what I’m talking about.

Your code so far

[1, [2], [3, [[4]]]] // the array in question

console.log(typeof arr[1]) // returns object
console.log(arr.filter(a => !isNaN(a))) // returns [ 1, [ 2 ] ] 
console.log(arr.filter(a => a >= 0)) // returns [ 1, [ 2 ] ]
console.log(arr.filter(a => Array.isArray(a))) // returns [ [ 2 ], [ 3, [ [Object] ] ] ]



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.

Challenge: Steamroller

Link to the challenge:

I think it has to do with abstract relational comparison, whereby the value is being converted into a primitive type, where the hint for the primitive is automatically number.

A more readable bit of this is Mozilla.

Hope this helps

1 Like

typeof will always return ‘object’ for an array, so don’t let that throw you. If you really need to know whether it is a regular object or an array then use Array.isArray().

An array with a single element will be coerced to its single value, so passing [2] into isNan() will be the same as isNaN(2) which will return false. But if the array you pass in has more than one value then you will get true for isNaN().

Same thing for the >= comparison, the array with a single element will be coerced to that element and thus [2] >= 0 is true.

1 Like

As another gotcha, remember that isNaN does not test is something is a number or not, it checks to see if it is NaN. When it tries to coerce “[3, [[4]]]” it can’t do it an it evaluates to NaN.

1 Like