In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.
In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in
if(value) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Videos
In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.
In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in
if(value) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:
+--------------------------------------------------------------------------+
| Argument Type | Result |
|---------------+----------------------------------------------------------|
| Undefined | false |
|---------------+----------------------------------------------------------|
| Null | false |
|---------------+----------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------+----------------------------------------------------------|
| Number | The result is false if the argument is +0, โ0, or NaN; |
| | otherwise the result is true. |
|---------------+----------------------------------------------------------|
| String | The result is false if the argument is the empty String |
| | (its length is zero); otherwise the result is true. |
|---------------+----------------------------------------------------------|
| Object | true |
+--------------------------------------------------------------------------+
From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.
If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:
if (!fields || fields.length === 0)
An important distinction to make is that the Type of null is Null.
(ignore typeof it returns "object" for null because of bad design and backwards compatibility)
11.9.3 The Abstract Equality Comparison Algorithm # โ The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
[... stripped]
- Return false.
The ES5 specification
Says that the comparison with null and a Boolean should return false because the Type of Null and Boolean are not the same, and none of the other steps in 11.9.3 apply so the default action of return false happens
The only case where the Type of x and y are different and either x or y is null but the == operation still returns true are
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
That means undefined == null returns true
Of special note:
There is an ES6:harmony proposal to fix typeof null
Actually I think he refers to the fact that typeof null == 'object', which is unfortunately the case. But that's a peculiarity of the typeof operator, not of null itself. Null is falsy value, but typeof returns "object" for it, according to the spec: http://bclary.com/2004/11/07/#a-11.4.3
Falsey values in JavaScript
false- Zero of
Numbertype:0and also-0,0.0, and hex form0x0(thanks RBT) - Zero of
BigInttype:0nand0x0n(new in 2020, thanks GetMeARemoteJob) "",''and``- strings of length 0nullundefinedNaNdocument.all(in HTML browsers only)- This is a weird one.
document.allis a falsey object, withtypeofasundefined. It was a Microsoft-proprietory function in IE before IE11, and was added to the HTML spec as a "willful violation of the JavaScript specification" so that sites written for IE wouldn't break on trying to access, for example,document.all.something; it's falsy becauseif (document.all)used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy? for details
- This is a weird one.
"Falsey" simply means that JavaScript's internal ToBoolean function returns false. ToBoolean underlies !value, value ? ... : ...; and if (value). Here's its official specification (2020 working draft) (the only changes since the very first ECMAscript specification in 1997 are the addition of ES6's Symbols, which are always truthy, and BigInt, mentioned above:
Argument type Result Undefined Return false.Null Return false.Boolean Return argument. Number If argument is +0,-0, orNaN, returnfalse; otherwise returntrue.String If argument is the empty String(its length is zero), returnfalse; otherwise returntrue.BigInt If argument is 0n, returnfalse; otherwise returntrue.Symbol Return true.Object Return true.
Comparisons with == (loose equality)
It's worth talking about falsy values' loose comparisons with ==, which uses ToNumber() and can cause some confusion due to the underlying differences. They effectively form three groups:
false, 0, -0, "", ''all match each other with==- e.g.
false == "",'' == 0and therefore4/2 - 2 == 'some string'.slice(11);
- e.g.
null, undefinedmatch with==- e.g.
null == undefinedbutundefined != false - It's also worth mentioning that while
typeof nullreturns'object',nullis not an object, this is a longstanding bug/quirk that was not fixed in order to maintain compatibility. It's not a true object, and objects are truthy (except for that "wilful violation"document.allwhen Javascript is implemented in HTML)
- e.g.
NaNdoesn't match anything, with==or===, not even itself- e.g.
NaN != NaN,NaN !== NaN,NaN != false,NaN != null
- e.g.
With "strict equality" (===), there are no such groupings. Only false === false.
This is one of the reasons why many developers and many style guides (e.g. standardjs) prefer === and almost never use ==.
Truthy values that actually == false
"Truthy" simply means that JavaScript's internal ToBoolean function returns true. A quirk of Javascript to be aware of (and another good reason to prefer === over ==): 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"). Since0 == false, if"0" == 0,"0" == false.new Number(0)andnew Boolean(false)- they're objects, which are truthy, but==sees their values, which== false.0 .toExponential();- an object with a numerical value equivalent to0- Any similar constructions that give you a false-equaling value wrapped in a type that is truthy
[],[[]]and[0](thanks cloudfeet for the JavaScript Equality Table link)
Some more truthy values
These are just a few values that some people might expect to be falsey, but are actually truthy.
-1and all non-zero negative numbers' '," ","false",'null'... all non-empty strings, including strings that are just whitespaceAnything from
typeof, which always returns a non-empty string, for example:typeof null(returns a string'object'due to a longstanding bug/quirk)typeof undefined(returns a string'undefined')
Any object (except that "wilful violation"
document.allin browsers). Remember thatnullisn't really an object, despitetypeofsuggesting otherwise. Examples:{}[]function(){}or() => {}(any function, including empty functions)Errorand any instance ofError- Any regular expression
- Anything created with
new(includingnew Number(0)andnew Boolean(false))
Any Symbol
true, 1, "1" and [1] return true when compared to each other with ==.
Don't forget about the non-empty string "false" which evaluates to true
- Data type of
nullisobject - Data type of
falseisboolean - Data type of
undefinedisundefined
So they are different.
Internally, JavaScript sets a value to one of six primitive data types:
- Undefined (a variable with no defined value)
- Null (a single null value)
- Boolean (true or false)
- Number (this includes Infinity and NaN โ not a number!)
- String (textual data)
- Symbol (a unique and immutable primitive new to ES6/2015)
- Everything else is an Object โ including arrays.
Here are the complete list of JavaScript falsy values
A common misconception
"...If double equalto (
==) operator only checks/compares for values & not for types..."
That's an incorrect assumption, though it's often repeated by people. In reality, the == does check types, and in fact pays far more attention to the types than a === comparison does.
See Abstract Equality Comparison Algorithm.
A == comparison doesn't do a simple toBoolean conversion. Rather it walks through a somewhat complex recursive algorithm, which, after checking the types, attempts to coerce the operands to the same type if they don't match.
The type coercion that it performs is very specific to the types of the operands. A different sequence of coercions can take place for different type pairs. Usually (but not always) it ends up ultimately coercing the operands down to number types.
Why !ing the operands changes things
When you manually coerce both operands using !, you're now doing a simple toBoolean conversion causing the types to match, which avoids the type coercive part of the algorithm, making it behave essentially like the Strict Equality Comparison Algorithm.
So the only way to predict the outcome of a == comparison when the types don't match is to understand that Abstract algorithm.
Don't forget about NaN
And FYI, there's one more "falsey" value to consider, NaN. Its == comparison will always be false, no matter what. Even when comparing to another NaN value, it'll be false.
undefined: means a variable was declared but has no value assigned
null: the value of null has been assigned, which means it has no value
false, '' and 0 I think you can probably work out what these mean.