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.

13 Responses to “Advanced Javascript: Logical Operators and truthy / falsy”

  1. [...] nFriedly posted an interesting refresher on JavaScript boolean evaluation of non-boolean values : Logical Operators and Truthy / Falsy. [...]

  2. nFriedly says:

    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.

  3. Johan says:

    Great article!

    I was always juggeling with if/else and (var ? var : ‘x’) statements.

    Thanks alot!

  4. nFriedly says:

    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/

  5. Chuck Denk says:

    So, && and || in JavaScript act essentially the same as they do in the C programming language, if I’m not mistaken.

  6. Andy Tjin says:

    So you say [] is truthy. But then why is the following true?
    [] == false

  7. nFriedly says:

    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!

  8. Max Bellasys says:

    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 :)

  9. nFriedly says:

    Awesome, glad it was helpful! And thanks for the compliment on the logo, it was designed by Charley Skira – http://www.charleyskira.com/

  10. “false” is evaluated as truthy by both PHP and javascript.

    That’s not true in JavaScript:

    var a = false,
    b = !!a; // false

  11. nFriedly says:

    Hi Eric, it looks like you’re confusing the boolean value false with the string value “false”:

    var boolean_false = false;
    !!boolean_false; // returns false
    
    var string_false = "false";
    !!string_false; // return true
    

    I edited the article to clarify that I’m referring to string values.

  12. Salman says:

    [] == false // true makes sense. First of all, keep these rules in mind:

    1) For == operations, when ONE operand is a boolean it is converted to the number 1 or 0
    2) For == operations, when ONE operand is a number the other operand is also converted to a number if possible
    3) Number("") i.e. attempting to convert "" to a number yields 0

    Now that you are comparing an object ([]) with a primitive (false), JavaScript engine converts the object to a primitive (using valueOf() or toString() methods) then compare the result. [] == false thus becomes "" == 0 which is true

    Likewise [] == true // false makes sense, it becomes "" == 1 which is false.

    See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators

  13. Robinson says:

    Truthy or Falsy works with lot of operators like Less than (<),Less than or equal to (),Greater than or equal (>=),Strict not equal (!==),Strict equal (===),Not equal (!=),Equal (==).

    (== and !=) are called as “standard equality operators”.

Leave a Reply

 


RSS nFriedly Web Development » Technical Blog