Alexander Solonik Alexander Solonik - 2 years ago 80
Javascript Question

Variable declaration using short circuiting

I was just going through a JQuery plugin and came across the following line of code:

var doAnimate = $.support.transition && animate

I do understand short circuiting, but is that a variable declaration using short circuiting ??

On asking somebody more experienced then me, I got the following reply:

If they loaded the transition library, use it, otherwise use animate.

I guess the value returned is not true or false , because i've heard short circuiting does't return true or false .

So if
is undefined, animate gets stored in

Is that how it works? I am really confused about this variable declaration and how it works. I do understand short circuiting in conditionals .

Answer Source

"If they loaded the transition library, use it, otherwise use animate."

What they meant was to use || operator.

var doAnimate = $.support.transition || animate;

What the above does is, it checks if $.support.transition is available, or loaded, use it, else use animate.

When we do expr1 && expr2, it returns expr1 if it is falsey; otherwise, returns expr2.

So, when you do var doAnimate = $.support.transition && animate;, if $.support.transition isn't loaded or is undefined, doAnimate will still hold $.support.transition, instead of animate.

If it is loaded, then animate will be used. This is contrary to what you want. That's where || comes into action.

When we do expr1 || expr2 it returns expr1 if it is truthy; otherwise, returns expr2.

So when we use || and if $.support.transition is loaded, it will be used, else animate will be used.

More on logical operators on MDN

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download