A quick tip to remove all falsy (false, null, undefined, 0, NaN or an empty string) items out of an array:

var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5]
var b=a.filter(Boolean); // [1,2,"b",{},3,5]

Since Boolean constructor is also a function, it returns either true for 'truthy' argument or false for 'falsy' argument.

For example:

Boolean(0) // false
Boolean(true) // true
Boolean(1) // true
Boolean("") // false
Boolean("false") // true. "false" is a regular, non-empty string

And writing


is actually the same as writing:

b = a.filter(function (x) { return Boolean(x) })


  • 符号计算
  • 表达式
  • console.log


'' ? 1 : 0 结果是 0, 记住了 '' 隐式转化 boolean 为 false。