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?
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.
This question could be generalized for JavaScript at large, rather than jQuery-specific.
The typical reasons to use bracket notation are when:
- The function/property name you want to reference is variable, in which case brackets can help you keep your code DRY
- The property/function name has characters making it impossible to access via dot notation.
Your use here seems like a novel variation of the first case-- you're avoiding repeating code by using a variable string value from a ternary operation to specify which function to execute.
It's a trade-off between explicit readability and DRY code, so the "best" choice will be subjective.
For some people, ternary isn't so tough to read. You are you can read this ? "one of them" : "not one of them"
. You could always throw a comment near any particularly long function chains for the benefit of people who have trouble digesting ternary.