Pergunta

In reference to the answer provided in Shorten code using Ternary Operators, I was wondering why the following ternary isn't recommended.

$('#myID')[(myVar1 === myVar2) ? 'addClass' : 'removeClass']('myClass');

Instead, the recommended answer reads:

$('#myID').toggleClass('myClass', myVar1 === myVar2);

To clarify, I understand the latter is better as it utilizes the second arg for toggleClass to make the evaluation. What I'm wondering is if the first example is generally not recommended due to it's readability or some other factor. Also, does the first ternary have a special name? I'm curious if it's called something special in case I ever have to search for it again.

Many thanks!

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top