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?
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:
This is very useful if you want to replace this:
With:
So in short, if
isEnabled()is truthy thenis_enabledwill be set to whateverisSupported()returns. IfisEnabled()is falsy, thenis_enabledwill be set to whatever that falsy value is.Also as Robert pointed out, there is short-circuiting:
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.