, , ,

In javascript (and some other languages for that matter) non-boolean values can behave as booleans under certain circumstances. This is often referred to as “truthy” or “falsy,” that is, it’s like a boolean true or false, but technically isn’t exactly the same, so it’s “kind of true” and “kind of false.” What am I talking about?

Okay, take this code:

var myStr = "hello";
if (myStr != "") {
	alert("string isn't empty!");

Okay, so this if statement basically tests that myStr isn’t empty, and displays an alert if that condition passes. Makes sense. But actually, an empty string is an example of something which is “falsy”, that is, within a test condition, "" evaluates to false. Therefore, the following code effectively produces the same result:

var myStr = "hello";
if (myStr == false) {
	alert("string isn't empty!");

That being the case, it is simpler to remove the comparative operator altogether:

var myStr = "hello";
if (!myStr) {
	alert("string isn't empty!");

This concept exists throughout javascript. Something (anything!) will either evaluate to true or false within a test condition. The following table gives a breakdown of values/types and their respective truthy/falsy result:

value typeof result
-1 number truthy
0 number falsy
1 number truthy
NaN number falsy
Infinity number truthy
true boolean truthy
false boolean falsy
“true” string truthy
“false” string truthy
“” string falsy
“-1” string truthy
“0” string truthy
“1” string truthy
“hello” string truthy
“null” string truthy
null object falsy
“undefined” string truthy
undefined undefined falsy
[] object truthy
[0] object truthy
new Array() object truthy
{} object truthy
{prop: 1} object truthy
new Object() object truthy
new Date() object truthy
function(){} function truthy
document.getElementsByTagName(“body”)[0] object truthy

With this in mind you can save a lot of verbose code, create much slicker test conditions and generally look like a better developer!