hamahama
hamahama

Reputation: 393

What does this expression mean in javascript?

$('.blocks','#grid').each(function (i) {
              $(this).stop().css({opacity:0}).delay(100).animate({
                'opacity': 1
              }, {
                duration: 2000,
                complete: (i !== row * cols - 1) ||
                function () {
                  alert('done');
                }

              });
            });

What does the "||" operator mean in the "complete" property of the animate function?

Upvotes: 2

Views: 174

Answers (4)

alex
alex

Reputation: 490243

It exploits short circuit evaluation. While the left hand side is truthy it won't bother evaluating the right hand side.

This is because with an OR, if one condition is truthy, it doesn't need to bother with additional conditions because it already knows enough information to answer the condition. They are also evaluated from left to right.

Also, in JavaScript, instead of the condition returning true or false, it returns the last operand it evaluated. You can see why this is useful.

Upvotes: 2

vol7ron
vol7ron

Reputation: 42109

The expression seems to be a fade in.

The logical OR || is similar to an else case of an if statement. If the left side evaluates to false, the function is created and an alert is called.


Given:

  • (i !== row * cols - 1) || function () { alert('done');  }
    

The function declaration would be assigned in this case:

  • false || function (){ alert('done'); }
    

Note, that "complete" property would not hold a value, just a function definition, you would need to call complete as something like complete(). For the function to be called if the left side is false, you'd have to surround it in parentheses and call it:

  • complete: (i !== row * cols - 1) || (function () {alert('done');})()
    

Note: The left hand side will only be false if something is undefined (i think), or if i turns out to equal rows*cols -1.

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

It's the logical OR operator, but it only evaluates the right-hand expression if the left-hand expression is false.

If the left-hand expression is true then it knows that the whole expression evaluates to true, so it doesn't bother evaluating (or executing) the right-hand expression.

Upvotes: 0

thescientist
thescientist

Reputation: 2948

|| is a logical operator http://www.w3schools.com/js/js_comparisons.asp

it will 'favor' the left hand side until the left hand condition is not met anymore, at which point it will execute the right side, which is an anonymous function that executes an alert.

Upvotes: 0

Related Questions