Logical Operators

Contact Us or call 1-877-932-8228
Logical Operators

Logical Operators

Logical operators allow you to evaluate a series of operands using AND and OR operations. These operations are called short-circuiting, because they stop evaluating an expression when the overall result has been determined (for example, in an AND operation, if the first value is false, then there is no way that the overall expression can be true, so processing of the expression stops; similarly for an OR operation if the first value is true).

This behavior treats all values as having a logical (true/false) aspect. The concept that a value is treated as true is called truthy, and behaving as false is called falsy.

Truthy and Falsy Values

In order to use logical operations and flow control successfully, it's important to understand which kinds of values are truthy and which kinds of values are falsy. Sometimes, values that seem like they should evaluate one way actually evaluate another.

Values That Act as True

'any string'   // any non-empty string, even '0' and 'false'
[]             // any array, even an empty array
{}             // any object, even an empty object
function() { } // any function
1;             // any non-zero number
true           // the literal true value

Values That Act as False

''             // an empty string
NaN            // JavaScript's Not-a-Number value
false          // the literal boolean value

You should note that "0" and "false" are truthy, since they are non-empty strings.

Logical AND and OR operators

In Javascript, && = AND while || = OR
var foo = 1;
var bar = 0;
var baz = 2;

foo || bar;   // foo OR bar, returns 1, which is truthy
bar || foo;   // bar OR foo, returns 1, which is truthy

foo && bar;   // foo AND bar, returns 0, which is falsy
bar && foo;   // bar AND foo, returns 0, which is falsy
foo && baz;   // foo AND baz, returns 2, which is truthy
baz && foo;   // baz AND foo, returns 1, which is truthy

Though it may not be clear from the example, the || operator returns the value of the first truthy operand, or, in cases where neither operand is truthy, it will return the last of both operands. The && operator returns the value of the first falsy operand, or the value of the last operand if both operands are truthy. In essence a logical operation evaluates to the last value it processed.

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.