Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  165] [ 7]  / answers: 1 / hits: 17728  / 12 Years ago, wed, july 18, 2012, 12:00:00

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?


More From » variables

 Answers
4

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.


[#84173] Tuesday, July 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
christianu questions
;