Skip to content

Instantly share code, notes, and snippets.

@mindfullsilence
Created August 12, 2015 19:03
Show Gist options
  • Save mindfullsilence/3a161f239abc493d698c to your computer and use it in GitHub Desktop.
Save mindfullsilence/3a161f239abc493d698c to your computer and use it in GitHub Desktop.
Falsey / Truthy JS Guide
Falsey values in JavaScript
false
0
-0
""
''
null
undefined
NaN
"Falsey" simply means that JavaScript's internal ToBoolean function returns false. ToBoolean underlies !value, value ? ... : ...; and if(value){...}else{...}.
For comparisons with == these form three groups:
false, 0, -0, "", '' all match each other with ==
e.g. false == "" and '' == 0
null, undefined match with ==
e.g. null == undefined but undefined != false
NaN doesn't match anything with == not even itself
e.g. NaN != NaN, NaN != false, NaN != null
Only false matches false with ===.
Truthy values that actually == false
"Truthy" simply means that JavaScript's internal ToBoolean function returns true. A quirk of Javascript to be aware of: it is possible for a value to be truthy (ToBoolean returns true), but also == false.
You might think if( value && value==false ){ alert("huh?"); } is a logical impossibility that couldn't happen, but it will, for:
"0" and '0' - they're non-empty strings, which are truthy, but Javascript's == matches numbers with equivalent strings (e.g. 42 == "42"). Since 0 == false, if "0"==0, "0"==false.
new Number(0) and new Boolean(false) - they're objects, which are truthy, but == sees their values, which == false.
0 .toExponential(); - an object with a numerical value equivalent to 0
Any similar constructions that give you a false-equaling value wrapped in a type that is truthy
[], [[]] and [0]
Some more truthy values
These are just a few values that some people might expect to be falsey, but are actually truthy.
-1 and all non-zero negative numbers
' ', " " and all non-empty strings, even if they're just whitespace
Anything from typeof, which always returns a non-empty string, for example:
typeof null (returns a string 'object')
typeof undefined (returns a string 'undefined')
Any object (except a literal null), including:
{}
[]
function(){} (any variable defined as a function, including empty functions)
Any regular expression
Anything created with new (including otherwise-falsey values created with new, see above)
true, 1, "1" and [1] return true when compared to each other with ==.
@mindfullsilence
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment