I have a variable and if that variable is a object I would like to call a method on that object, if not I want to do nothing.
I’m wondering if there is any reason why I shouldn’t do it like this.
var foo = null; //////////////////////////////////////////////// // some code that could change foo to a object //////////////////////////////////////////////// foo && foo.bar();
Advertisement
Answer
The quick answer is yes, foo && foo.bar() won’t throw an exception if foo is null, and if foo is non-null, bar() will be evaluated, and it’s value will be the value of the expression.
Longer answer is that any value can be interpreted as a boolean, in the sense that every value is either truthy or falsey, and that the boolean operators do short-circuit evaluation — left to right, if we see a false && or a true ||, there’s no reason to carry on evaluating.
One last fact is that the value of boolean expression is the value of the expression where the short-circuit happened.