Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Short-Circuit (Strange use of II / OR operator)

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.

like image 960
VSO Avatar asked Aug 03 '15 19:08

VSO


People also ask

Does JavaScript use short circuit?

In JavaScript, short-circuiting is the evaluation of an expression from left to right with || and && operators. If the condition is met and the rest of the conditions won't affect the already evaluated result, the expression will short-circuit and return that result (value).

Does JS do lazy evaluation?

Iterators in JavaScript (since ECMAScript 6) are what make it possible to lazy evaluate and create user-defined data sequences. Iteration is a mechanism for traversing data. Iterators are pointers for traversing elements of data structure, called Iterable.

Does or operator short circuit?

The || OR operator is also a short-circuit operator. Since OR evaluates to true when one or both of its operands are true , short-circuit evaluation stops with the first true . The OR operator comes in a non-short-circuit version as well: | (this is a single vertical bar.)


2 Answers

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.

like image 178
Maximillian Laumeister Avatar answered Oct 23 '22 04:10

Maximillian Laumeister


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.

like image 45
kwah Avatar answered Oct 23 '22 05:10

kwah