Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shorthand to call method if object exists

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();
like image 497
cmac Avatar asked Jul 28 '16 18:07

cmac


2 Answers

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">
like image 50
revolver Avatar answered Sep 24 '22 21:09

revolver


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.

like image 26
danh Avatar answered Sep 23 '22 21:09

danh