Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: What's the meaning of comparison in following code block - callback && function() {callback.call();}

Seeing this block from jQuery.scrollTo.js library (in v1.4 at line 184).

function animate( callback ){
    $elem.animate( attr, duration, settings.easing, callback && function(){
        callback.call(this, target, settings);
    });
};

Curious to know how the comparison is going to work with

callback && function() {callback.call(...)}; 

and what's exactly the meaning behind this. Thanks in advance.

like image 354
Anmol Saraf Avatar asked Dec 28 '22 10:12

Anmol Saraf


2 Answers

The callback && function() {callback.call(...)}; is doing two things:

  • testing whether a callback has been defined and
  • if it has, calling it in the correct context

JavaScript has a feature called "short-circuiting logical expressions". If a part of a logical expression cannot change the overall result, it is not going to be evaluated.

If callback is undefined, then it evaluates to false in the context of a logical expression (it's "falsy"). So the expression becomes the equivalent of false && ..., in which case it does not matter anymore what ... actually is, the result will always be false †1. JavaScript is not looking at the ... in this case.

If callback is not undefined (but a function), the first part of the logical expression evaluates to true (it's "truthy"). At this point JavaScript evaluates the .... The overall result happens to be a function expression. The function expression results in an anonymous function, which is then passed to jQuery's animate().

The callback.call() executes callback and determines the meaning of this within callback. So callback.call(this) makes sure that this refers to the same object as in the outer function.


†1To be absolutely correct: The overall result of the expression will not be false, it will be undefined.

like image 172
Tomalak Avatar answered May 16 '23 18:05

Tomalak


callback && function() {callback.call(...)}; 

This will check if the callback is truthy (is not false, 0, "", null, undefined, NaN) and if it is truthy and second part of the statement will be evaluated which will return function that will be passed in as a argument.

Example:

var test = true && function() {};
console.log(typeof test); // "function"
like image 42
kubetz Avatar answered May 16 '23 18:05

kubetz