Is it valid to use && instead of if?

前端 未结 3 1651
萌比男神i
萌比男神i 2021-01-20 01:01

I am using && like this and it works

typeof foo === \'function\' && foo(); //if foo exist then call it

instead

相关标签:
3条回答
  • 2021-01-20 01:09

    The linter's job is to look out for things that while syntactically valid may not follow recommended best practices.

    "Expected an assignment or function call" probably means that it expects foo to be foo() or foo = in the first part, that seeing it without a call is, in its opinion, a mistake.

    You're free to do whatever you want. Short-circuit evaluation behaves predictably, so it's going to work, but it may be confusing to people unfamiliar with that style.

    0 讨论(0)
  • 2021-01-20 01:19

    You could use a void operator. This evaluates the expression and returns undefined.

    void (foo && foo());
    

    var foo;
    
    void (foo && foo());
    
    foo = () => console.log('foo');
    
    void (foo && foo());

    0 讨论(0)
  • 2021-01-20 01:30

    In the background there is a bit more with the && thingy, but for 99% of the cases it is perfectly fine to do it that way, just like this one.

    Now as a personal opinion, for a one-liner I prefer it the && way instead of the if one, because I can't stand if keyword without a block below it hehe.

    If you know what you are doing, linters are too picky sometimes.

    0 讨论(0)
提交回复
热议问题