The first example is using a ternary operator to determine the property string that will be passed into bracket-notation. This is no different than any other ternary use that assigns a value:
var argmnt = "emphasize",
method = condition ? "addClass" : "removeClass" ;
$( selector )[ method ]( argmnt );
The only difference is that you're placing the ternary itself within the brackets:
$( selector )[ condition ? "addClass" : "removeClass" ]( argmnt );
This does make the code a little more difficult to read, and it unnecessarily replicates the functionality of another perfectly good method: $.fn.toggleClass
.
I cannot peek into the mind of others, but I suspect this is why the author of your referenced answer chose the easier, less-verbose, solution.
More on Bracket-Notation
Object keys allow more characters and flexibility than dot-notation permits. For instance, while first-name
is a valid key, you cannot access it with dot-notation like person.first-name
. This is where bracket-notation comes in handy: person['first-name']
is entirely valid.
We can also use bracket-notation to do inline-evaluations or hold variables:
var method = "addClass";
$( selector )[ method ]( argmnt );
This is the same as writing $( select ).addClass( argmnt ), but we're able to conditionally determine which method will be called:
$.fn.addClass, or
$.fn.removeClass`.
You may also see this approach taken when accessing items in an array:
var values = [ "Stack", "Overflow" ];
el.textContent = values[ (1 + values.indexOf( el.textContent )) % values.length ];
Here too we're performing an ad-hoc evaluation within the square brackets rather than storing the results in a variable, and then passing that in.
As long as your code is short and concise, this isn't all that bad. But be careful, things can quickly get out of hand and your code and rapidly become difficult to visually parse, and thus problematic to maintain for yourself or future developers on the project.