ToNumber

true becomes 1 and false becomes 0. undefined becomes NaN, but (curiously) null becomes 0
Objects (and arrays) will first be converted to their primitive value equivalent, and the resulting value (if a primitive but not already a number) is coerced to a number according to the ToNumber rules just mentioned.

To convert to this primitive value equivalent, the ToPrimitive abstract operation (ES5 spec, section 9.1) will consult the value (using the internal DefaultValue operation -- ES5 spec, section 8.12.8) in question to see if it has a valueOf() method. If valueOf() is available and it returns a primitive value, that value is used for the coercion. If not, but toString() is available, it will provide the value for the coercion.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

If neither operation can provide a primitive value, a TypeError is thrown.

ToBoolean

Falsy Values

All of JavaScript's values can be divided into two categories:

  1. values that will become false if coerced to boolean
  2. everything else (which will obviously become true)

the so-called "falsy" values list:

  • undefined
  • null
  • false
  • +0, -0, and NaN
  • ""

That's it. If a value is on that list, it's a "falsy" value, and it will coerce to false if you force a boolean coercion on it.

By logical conclusion, if a value is not on that list, it must be on another list, which we call the "truthy" values list. But JS doesn't really define a "truthy" list per se. It gives some examples, such as saying explicitly that all objects are truthy, but mostly the spec just implies: anything not explicitly on the falsy list is therefore truthy.

var a = "false";
var b = "0";
var c = "''";

var d = Boolean( a && b && c );

d;

Falsy Objects

Wait a minute, that section title even sounds contradictory. I literally just said the spec calls all objects truthy, right? There should be no such thing as a "falsy object."

What could that possibly even mean?

You might be tempted to think it means an object wrapper (see Chapter 3) around a falsy value (such as "", 0 or false). But don't fall into that trap.
"falsy objects" are not just objects wrapped around falsy values,

conclusion

![]
// false
!{}
// false
!function(){}
// false
!''
// true
Boolean('')
// false
!null
// true
!undefined
// true
!0
// true
'fasle' && '0' && "''"
// "''"
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄