JavaScript combining && statements in a variable to be true or false

In Javascript the && and || operators are slightly strange. It depends on if the value is "falsy" (zero, undefined, null, empty string, NaN) or truthy (anything else, including empty arrays).

With && if the first value is "falsy", then the result of the operation will be the first value, otherwise it will be the second value. With || if the first value is "falsy" then the result of the operation will be the second value, otherwise it will be the first value.

Example:

var a = 5 && 3; // a will be 3
var a = 0 && 7; // a will be 0

var a = 1 || 2; // a will be 1
var a = 0 || 2; // a will be 2

This is very useful if you want to replace this:

if (x == null){
  x = 5;
}

With:

x = x || 5;

So in short, if isEnabled() is truthy then is_enabled will be set to whatever isSupported() returns. If isEnabled() is falsy, then is_enabled will be set to whatever that falsy value is.

Also as Robert pointed out, there is short-circuiting:

var x = 5 || infinite_loop();
var x = false && infinite_loop();

In both cases, the infinite_loop() call doesn't happen, since the two operations are short-circuited - || doesn't evaluate the second value when the first value is truthy, and && doesn't evaluate the second value when the first value is falsy.


The result of false && true is false.


If isEnabled() is false and you use && then isSupported() will never be called because the evaulation will short circuit.