Logical operators allow you to evaluate a series of comparators using AND and OR operations.


Though it may not be clear from Example 2.10, “Logical AND and OR operators”, the || operator returns the value of the first truthy comparator, or false if no comparator is truthy. The && operator returns the value of the last false comparator, or the value of the last comparator if all values are truthy. Essentially, both operators return the first value that proves them true or false.

Be sure to consult the section called “Truthy and Falsy Things” for more details on which values evaluate to true and which evaluate to false.

Note

You'll sometimes see developers use these logical operators for flow control instead of using if statements. For example:

// do something with foo if foo is truthy
foo && doSomething(foo);

// set bar to baz if baz is truthy;
// otherwise, set it to the return
// value of createBar()
var bar = baz || createBar();

This style is quite elegant and pleasantly terse; that said, it can be really hard to read, especially for beginners. I bring it up here so you'll recognize it in code you read, but I don't recommend using it until you're extremely comfortable with what it means and how you can expect it to behave.