Search code examples
javascriptjquerychaining

dot vs bracket notation in jquery method chaining


Suppose that I have a long chain of jquery methods and want to add extra call of one of two methods (e.g. show or hide) depending on some boolean condition.

There are two ways to do it:

1) Dot notation: store the method chain in a variable, then call extra method (resolved by if...else construct or ternary operator) with this variable using dot notation.

Code:

var $tmp = $el._long_()._method_()._chain_();
if (condition) $tmp.show();
else $tmp.hide();

2) Bracket notation: append extra call of method (resolved by ternary operator) using square bracket notation.

Code:

$el._long_()._method_()._chain_()[condition? 'show' : 'hide']();

I used to use the first one, especially if $tmp variable is used elsewhere. But the second way seems to be more concise though less readable.

What would be the best choice for such case?


Solution

  • eslint prefers dot-notation:

    In JavaScript, one can access properties using the dot notation (foo.bar) or square-bracket notation (foo["bar"]). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.

    IMO, putting tertiary logic inside of bracket's is a little too cute and hard to read.