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();
With ES6, you can combine optional chaining operator with call:
foo?.bar?.call()
If you want to pass arguments, keep in mind that the first one in call assigns this
in function call
var foo = {
bar: function(x) { return x; }
};
first.value = foo?.bar?.call(0,42); // 42
second.value = foo?.baz?.call(0,42); // undefined, no error
<input id="first">
<input id="second">
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With