Why Array.filter(Number) filters zero out in javascript?

  • A+
Category:Languages

I'm trying to filter all non-numeric out from array. We can see desired output when using typeof. But with Number, it filters zero out.

Here's the example (tested in Chrome Console):

[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number) // Which output with zero filtered out: [-1, 1, 2, 3, 4]  // 0 is filtered 

If we use type of, it doesn't filter zero, which was expected

// code [-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(n => typeof n === 'number') // output [-1, 0, 1, 2, 3, 4, 0] 

My question:

  1. What is the difference between the 'Number' and 'type of' approach?

  2. Number filter zero, but 'Number' itself literally containing zero, and this makes me confusing.

 


Because 0 is one of the many falsy values in javascript

All these conditions will be sent to else blocks:

if (false) if (null) if (undefined) if (0) if (NaN) if ('') if ("") if (``) 

From the Array.prototype.filter() documentation:

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true

In your case the callback function is the Number. So your code is equivalent to:

[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(a => Number(a)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: