Complex javascript ternaries

Regarding the answer given in Shorten the code using ternary operators , I was wondering why the next triple is not recommended.

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

Instead, the recommended answer reads:

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

To clarify, I understand that the latter is better, since it uses the second arg for toggleClass to evaluate. I am wondering if the first example is usually not recommended because of its readability or some other factor. Also, does the first tee have a special name? I am curious if he called something special, if I ever need to look for him.

Many thanks!

+4
source share
1 answer

, . , :

var argmnt = "emphasize",
    method = condition ? "addClass" : "removeClass" ;

$( selector )[ method ]( argmnt );

, :

$( selector )[ condition ? "addClass" : "removeClass" ]( argmnt );

, : $.fn.toggleClass.

, , , .

, -. , first-name , , person.first-name. : person['first-name'] .

inline- :

var method = "addClass";
$( selector )[ method ]( argmnt );

, $( select ).addClass( argmnt ), but we're able to conditionally determine which method will be called: $. fn.addClass , or $. fn.removeClass`.

:

var values = [ "Stack", "Overflow" ];
el.textContent = values[ (1 + values.indexOf( el.textContent )) % values.length ];

, , .

, . , - , .

+5

Source: https://habr.com/ru/post/1533085/


All Articles