Truthy and Falsy

Contact Us or call 1-877-932-8228
Truthy and Falsy

Truthy and Falsy

JavaScript, as we already know, has a boolean data type, which has only two possible values: true or false. Boolean expressions (e.g., a == b) also evaluate to a boolean value. But that's not the entire story.

When used in a boolean context (e.g, an if condition) non-boolean expressions are implicitly converted to booleans. This process is called Type Coercion. For example, in the expression if (1) { alert('Hi!') }, 1 is interpreted as true, so the alert will pop up. The value 1 is said to be truthy. The value 0, on the other hand, is said to be falsy.

When used in a context that expects a boolean value, any JavaScript expression can be used. See below:

Code Sample:

---- C O D E   O M I T T E D ----

var truthies = [

var foo;
var falsies = [
---- C O D E   O M I T T E D ----

	for (var t=0; t<truthies.length; t++) {
		document.write("<li>" + truthies[t] + " : " + Boolean(truthies[t]) + "</li>");
---- C O D E   O M I T T E D ----

	for (var f=0; f<falsies.length; f++) {
		document.write("<li>" + falsies[f] + " : " + Boolean(falsies[f]) + "</li>");
---- C O D E   O M I T T E D ----

Open the above page in a browser and you'll see how the different values get evaluated when implicitly converted to booleans. The table below shows how different values are converted:

Truthy-Falsy Values
Value Truthy-Falsy Explanation
0 falsy 0 is falsy.
"0" truthy Non-zero-length strings are truthy.
-1 truthy All numbers but 0 are truthy.
null falsy null is falsy.
"null" truthy Non-zero-length strings are truthy.
undefined falsy undefined is falsy.
"undefined" truthy Non-zero-length strings are truthy.
NaN falsy NaN is falsy.
"NaN" truthy Non-zero-length strings are truthy.
Infinity truthy Infinity is a reserved word and is a non-zero number.
5/0 truthy 5/0 evaluates to Infinity.
"" (empty string) falsy Zero-length strings are falsy.
"false" truthy Non-zero-length strings are truthy.

Type coercion is the reason we have the === (triple-equal or strictly equal) comparison operator in JavaScript. The regular equality operator == applies type coercion and sometimes your comparisons will not result as expected. Look at the following sample code:

Code Sample:

---- C O D E   O M I T T E D ----

var num = 0;
if (num == "") {
	alert('Hey, I did not expect to see this.');
if (num === "") {
	alert('This will not be displayed.');
---- C O D E   O M I T T E D ----

In the first if conditional, we compare two falsy values, and the type coercion will resolve both of them to false, causing the result of the comparison to be true, which is probably not the original intent of the code.

To detect the type difference (string vs. number) we would need to use the triple equal operator, as shown in the second if statement.