您的位置:首页 > Web前端 > JavaScript

Truthy and Falsy: When All is Not Equal in JavaScript

2014-09-06 04:46 561 查看
http://www.sitepoint.com/javascript-truthy-falsy/





Craig Buckler

Published July 1, 2009

TweetSubscribe


Like
most computer languages, JavaScript supports Boolean data types; values which can be set to true or false. In addition, everything in JavaScript has an inherent Boolean value, generally known as either truthy orfalsy.
Handling truthy and falsy values can be a little quirky, especially when comparing variables. Understanding some of the more bizarre rules can help when debugging complex client-side applications.


Truthy and Falsy Values

The following values are always falsy:

false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)

All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
var a = !!(0); // variable is set to false
var b = !!("0"); // true


Comparing Falsy Values

Falsy values follow some slightly odd comparison rules which can lead to errors in program logic.

The falsy values false, 0 (zero), and "" (empty string) are all equivalent and can be compared against each other:
var c = (false == 0); // true
var d = (false == ""); // true
var e = (0 == ""); // true


The falsy values null and undefined are not equivalent to anything except themselves:
var f = (null == false); // false
var g = (null == null); // true
var h = (undefined == undefined); // true
var i = (undefined == null); // true


Finally, the falsy value NaN is not equivalent to anything — including NaN!
var j = (NaN == null); // false
var k = (NaN == NaN); // false


You should also be aware that
typeof(NaN)
returns "number". Fortunately, the core JavaScript
function
isNaN()
can be used to evaluate whether a value is NaN or not.

If in doubt…

Use strict equal (===) and strict not equal (!==) in situations where truthy or falsy values could lead to logic errors. These operators ensure that the objects are compared by type and by value.
var l = (false == 0); // true
var m = (false === 0); // false


Has truthy or falsy logic ever caused you grief in JavaScript code?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐