# 爱彼迎 js 规范
# Comparison Operators & Equality
15.2 Conditional statements such as the
ifstatement evaluate their expression using coercion with theToBooleanabstract method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
'', otherwise true
if ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true }15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
15.4 For more information see Truth Equality and JavaScript by Angus Croll.