0

I am ramping up on some code and found this structure multiple times throughout the code: y && y.someProp && y.someFunction();:

  $rootScope.funct = function() {
      $timeout(function() {
        var y = service.doSomething();
        y && y.someProp && y.someFunction();
      });
    } else {
      var y = service.doSomething();
      y && y.doSomethingElse();
    }
  };

What is the purpose of this? Does it stop execution of the program if both y && something else both don't complete or are otherwise falsey?

user3871
  • 12,432
  • 33
  • 128
  • 268

2 Answers2

3

It is a shorthand for the following:

if (y && y.someProp) {
    y.someFunction() // Call someFunction
}

So if y has a value that is not falsy and y.someProp is not falsy then it calls the someFunction function. It is a shorthand that some prefer and others don't.

kjonsson
  • 2,799
  • 2
  • 14
  • 23
2

Basically just a shorthand way to use short-circuiting to ensure you don't invoke the method on a null or undefined object. If y is falsey y.foo() is not invoked.

y && y.foo();

is functionally doing the same as

if (y) y.foo();
PMV
  • 2,058
  • 1
  • 10
  • 15