JavaScript
Article
By Craig Buckler

Truthy and Falsy: When All is Not Equal in JavaScript

By Craig Buckler

JavaScript-truthy-falsyLike 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 or falsy. 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.

--ADVERTISEMENT--

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?

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account