Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

just a quick question. I cannot find anything relating to this since I don't really see how to explain it... but, if I combine two bool values using an && to make another variable, what will happen?

var is_enabled = isEnabled() && isSupported();

If isEnabled() is false and isSupported() is true, will it equal false?

like image 527
Anonymous Avatar asked Jul 18 '12 16:07

Anonymous


2 Answers

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.

like image 192
robbrit Avatar answered Oct 08 '22 05:10

robbrit


The result of false && true is false.

like image 23
Atanas Korchev Avatar answered Oct 08 '22 04:10

Atanas Korchev