Search code examples
javascriptif-statementampersandshorthanddouble-ampersand

"if" shorthand with double ampersand


I have seen these lines code.

this.tween && this.tween.kill(),
this.tween = TweenMax.to(object, 1, {
  ...
})

Is that a shorthand for

if(this.tween){
  this.tween.kill();
}
this.tween = TweenMax.to(object, 1, {
  ...
})

thanks ;)


Solution

  • Yes, the two are equivalent in execution.

    function test(value) {
      console.log(value);
      
      value && console.log("\texecute using AND");
      if (value) console.log("\texecuted using if");
    }
    
    test(true);
    test(false);
    test("string");
    test(""); //empty string
    test(0);
    test(null);
    test(undefined);
    test(1);
    test({});

    However, with that said, it's not idiomatic usage of JavaScript. So you probably shouldn't be using this construct as it can throw other developers off. Your example illustrates that well, a code that looks like

    function f (condition) {
      condition && one(),
      two();
    }
    
    function one() {
      console.log("one");
    }
    
    function two() {
      console.log("two")
    }
    
    f(false);
    f(true);

    This is indeed effectively

    function f(condition) {
      if (condition) {
        one();
     }
    
      two();
    }
    

    So, one() would be executed some times, while two would always be executed. However, without knowing the precedence rules, it could seem like both one() and two() would be executed conditionally. This is an easy mistake to make and even easier if it's a complex conditions and logic

    person.account.moneyAmount > 0 && creditor.getDebt(person).moneyOwed > 0 && person.account.moneyAmount > creditor.getDebt(person).moneyOwed  && (deductTaxes(payAndReturnAmount(person, creditor)), printStatement()), printHello()
    

    This is only slightly exaggerated but it's entirely possible to end up in a similar situation. If your code is as simple as a single condition and a single action then you save 2 bytes from using an inline condition vs an if statement

    condition && action()
    if (condition) action()
                         ^^
    "extra" characters __||