Advanced Javascript: Logical Operators and truthy / falsy
July 7th, 2009 By nFriedly
Nearly every website on the internet uses javascript in some form or fashion. Yet very few people, even those who write it and teach it, have a clear understanding of how javascript works!
Logical Operators are a core part of the language. We’re going to look at what logical operators are, what “truthy” and “falsy” mean, and how to use this to write cleaner, faster and more optimized javascript.
Javascript Logical Operators
In traditional programming, operators such as && and || returned a boolean value (true or false). This is not the case in javascript. Here it returns the actual object, not a true / false. To really explain this, I first have to explain what is truthy and what is falsy.
Truthy or Falsy
When javascript is expecting a boolean and it’s given something else, it decides whether the something else is “truthy” or “falsy”.
An empty string (''), the number 0, null, NaN, a boolean FALSE, and undefined variables are all “falsy”. Everything else is “truthy”.
var emptyString = ""; // falsy
var nonEmptyString = "this is text"; // truthy
var numberZero = 0; // falsy
var numberOne = 1; // truthy
var emptyArray = []; // truthy, BUT []==false is true. More below.
var emptyObject = {}; // truthy
var notANumber = 5 / "tree"; // falsy
// NaN is a special javascript object for "Not a Number".
function exampleFunction(){
alert("Test");
}
// examleFunction is truthy
// BUT exampleFunction() is falsy because it has no return (undefined)
Gotchas to watch out for: the strings “0″ and “false” are both considered truthy. You can convert a string to a number with the parseInt() and parseFloat() functions, or by just multiplying it by 1.
var test = "0"; // this is a string, not a number (test == false); // returns false, meaning that test is truthy (test * 1 == false); // returns true, meaning that `test * 1` is falsy
As one commenter mentioned, arrays are particularly weird. If you just test it for truthyness, an empty array is truthy. HOWEVER, if you compare an empty array to a boolean, it becomes falsy:
if([] == false){
// this code runs
}
if( [] ) {
// this code also runs
}
if([] == true){
// this code doesn't run
}
if( ![] ) {
// this code also doesn't run
}
Another commenter pointed out an additional gotcha to watch out for: while javascript evaluates empty arrays as true, PHP evaluates them as false.
PHP also evaluates “0″ as falsy. (However the string “false” is evaluated as truthy by both PHP and javascript.)
<?php $emptyArray = array(); // falsy in PHP $stringZero = "0"; // falsy in PHP ?>
How Logical Operators Work
Logical OR, ||
The logical OR operator, ||, is very simple after you understand what it is doing. If the first object is truthy, that gets returned. Otherwise, the second object gets returned.
("test one" || "test two"); // returns "test one"
("test one" || ""); // returns "test one"
(0 || "test two"); // returns "Test two"
(0 || false); // returns false
Where would you ever use this? The OR operator allows you to easily specify default variables in a function.
function sayHi(name){
var name = name || "Dave";
alert("Hi " + name);
}
sayHi("Nathan"); // alerts "Hi Nathan";
sayHi(); // alerts "Hi Dave",
// name is set to null when the function is started
Logical AND, &&
The logical AND operator, &&, works similarly. If the first object is falsy, it returns that object. If it is truthy, it returns the second object.
("test one" && "test two"); // returns "test two"
("test one" && ""); // returns ""
(0 && "test two") // returns 0
The logical AND allows you to make one variable dependent on another.
var checkbox = document.getElementById("agreeToTerms");
var name = checkbox.checked && prompt("What is your name");
// name is either their name, or false if they haven't checked the AgreeToTerms checkbox
// IMPORTANT NOTE: Internet Explorer 8 breaks the prompt function.
Logical NOT, !
Unlike && and ||, the ! operator DOES turn the value it receives into a boolean. If it receives a truthy value, it returns false, and if it receives a falsy value, it returns true.
(!"test one" || "test two"); // returns "test two"
// ("test one" gets converted to false and skipped)
(!"test one" && "test two"); // returns false
// ("test one" gets converted to false and returned)
(!0 || !"test two"); // returns true
// (0 gets converted to true and returned)
Another useful way to use the ! operator is to use two of them – this way you always get a true or a false no matter what was given to it.
(!!"test"); // returns true // "test" is converted to false, then that is converted to true (!!""); // returns false // "" is converted to true, and then that true is converted to false (!!variableThatDoesntExist); // returns false even though you're checking an undefined variable.
Javascript Optimization
Need any help optimizing the Javascript and AJAX on your website? Get in touch with your friendly neighborhood javascript expert for ideas on how to optimize your site and a free quote.

[...] nFriedly posted an interesting refresher on JavaScript boolean evaluation of non-boolean values : Logical Operators and Truthy / Falsy. [...]
Thanks for pointing the differences between php and javascript. I updated the article to point out how php evaluates empty arrays and “0″ as falsy.
Great article!
I was always juggeling with if/else and (var ? var : ‘x’) statements.
Thanks alot!
Thanks, I just published a new article on objects, arrays & array-like objects that I was writing when your comment came in:
http://nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/
So, && and || in JavaScript act essentially the same as they do in the C programming language, if I’m not mistaken.
So you say [] is truthy. But then why is the following true?
[] == false
Because JavaScript is weird…
alert([] == false) // true
alert([] == true) // false
alert( ( [] ) ? ‘truthy’ : ‘falsy’ ) // truthy
I’ll append the original article though, thanks for pointing it out!
Thanks for your post. I really appreciate finding an advanced reference like this. It helped me debug my latest project– you don’t get this in the dictionary definitions (without a lot of trial and error). So I appreciate your resource here. Nice Logo, too, by the way
Awesome, glad it was helpful! And thanks for the compliment on the logo, it was designed by Charley Skira – http://www.charleyskira.com/
“false” is evaluated as truthy by both PHP and javascript.
That’s not true in JavaScript:
var a = false,
b = !!a; // false
Hi Eric, it looks like you’re confusing the boolean value false with the string value “false”:
I edited the article to clarify that I’m referring to string values.