Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript square bracket function call

Was browsing the jQuery source code when I met this line:

jQuery(this)[ state ? "show" : "hide" ]();

Are there any advantages over

state ? jQuery(this).show() : jQuery(this).hide();

?

Standalone example:

var object = {
    foo: function() {
        alert('foo');
    },

    bar: function() {
        alert('bar');
    }
};  


object[true ? 'foo' : 'bar']();
object[false ? 'foo' : 'bar']();
like image 912
DADU Avatar asked Jul 03 '11 21:07

DADU


3 Answers

There's no advantage in performance. But there's an advantage in length of code (if you see it as an advantage), and DRY principle (don't repeat code) specially if you have many parameters in your functions.

Consider the following:

obj[ cond ? "foo" : "bar" ]("param1", "param2", "param3");

Versus:

cond ? obj.foo("param1", "param2", "param3") : obj.bar("param1", "param2", "param3");

As you can see, you repeat 'a lot' of code in the second way

Hope this helps. Cheers

like image 75
Edgar Villegas Alvarado Avatar answered Oct 23 '22 01:10

Edgar Villegas Alvarado


In your example, there is no difference between

jQuery(this)[ state ? "show" : "hide" ]();

and

state ? jQuery(this).show() : jQuery(this).hide();

However, squares can be used to call a function without it's name:

var myFunctionName = 'show';
jQuery(this)[ myFunctionName ]();

Why this is useful ? In the above example, its totally useless. But we can find some situations where it could be nice:

// list of available methods
var effects = [ 'hide', 'slideUp', 'fadeOut' ];

// get a random index between 0 and effects.length-1 (2 in this case)
var randomIndex = Math.floor(Math.random() * (effects.length)); 

// get the method name
var methodToCall = effects[ randomIndex ];

jQuery(this)[ methodToCall ]();

This snippet will choose one random method and call that method over the jQuery object. Isn't that nice ? :)

like image 25
pomeh Avatar answered Oct 23 '22 01:10

pomeh


Are there any advantages

No, other than slightly shorter code, and not repeating jQuery(this).

However the repetition could be mitigated by declaring e.g. $this first.

I don't find this pattern particularly easy to read, so the only time I would use it myself is if the argument list is non-trivial, and not dependent on which method is being invoked.

like image 41
Alnitak Avatar answered Oct 23 '22 00:10

Alnitak