6

I ran into this piece of code:

<a  ng-click= "item.statusId !== itemStatus.in || transfer()">

I guess we can generalize as:

<element ng-click = "someVar !== someValue || doStuff()">

I then found this article on short circuits and another more focused one once I knew what they are called. However, I still don't get it.

Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement? (This is the main question I am asking, everything else is extra).

I guess that part I don't get is whether the compiler interprets this code differently or it still evaluates to false and just runs the function. Not even sure how to phrase Q.

VSO
  • 11,546
  • 25
  • 99
  • 187

2 Answers2

4

Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement?

It's effectively shorthand for an if statement, and you intuited correctly why it works. For more details on short-circuit evaluation in JavaScript, see this Stack Overflow question.

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Thanks, I read that already though. I understand why it works, roughly. Is it bad practice to use it? – VSO Aug 03 '15 at 19:34
  • @VSO Looks like the consensus is that [it is not very good practice to use it as a control structure](https://programmers.stackexchange.com/questions/109138/is-it-bad-practice-to-use-short-circuit-evaluation-instead-of-an-if-clause) like that. – Maximillian Laumeister Aug 03 '15 at 19:36
  • Looks like it's just what the "cool kids" use from reading that link. I don't see any serious complaints, but it did confuse me at first, so the posts saying it confuses noobs are valid =) Anyway, thanks for the help. – VSO Aug 03 '15 at 19:45
1

That code is equivalent to:

//Note the intentional and explicit use of `== false` to mean falsy (NOT `=== false` to indicate strict equality test for false)
if( (item.statusId !== itemStatus.in) == false ) {
 transfer();
}

It is an interesting means of executing a function only when a condition is falsy.

There are many different examples of this around on StackOverflow, and is not specific to AngularJS.

Community
  • 1
  • 1
kwah
  • 1,149
  • 1
  • 13
  • 27