New jQuery Syntax

var inital = newsletter.is(":checked");
var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");

Can somebody provide a resource about this syntax.

$(“#newsletter_topics”)[inital ? “removeClass” : “addClass”](“gray”)

Normally we write that like this know

var inital = newsletter.is(":checked");
var topics = inital ? $("#newsletter_topics").removeClass("gray") : $("#newsletter_topics").addClass("gray");

But that syntax is different. In jquery validation plugin use that syntax. Refer Line 83 in below metioned code.

The confusing part is an inline ternary operator, which is in the square brackets.
Otherwise it’s standard jQuery.

[inital ? “removeClass” : “addClass”]
when I see ? and :, I know this is the ternary operator:

if inital is true, it resolves to removeClass, if it’s false, to addClass.

Does that help?

I`ve updated my comment @sipofwater

This is confusing, but easy to understand if you explore the code a bit. I copied the code example to a CodePen below:

On line 70, I’m just logging the result of $("#newsletter_topics") to the console, but it won’t tell you much right away. It’s an array-like object, but we’re not passing a number into the brackets (which would make sense for an array). Instead, we’re passing a string, as though it were an object and we were accessing a property. Indeed, if you expand the object’s prototype, you’ll find two properties, removeClass and addClass, which are functions. So, the result of $("#newsletter_topics")[inital ? "removeClass" : "addClass"] is a function, and to that function we’re passing the string “gray”.

1 Like

Thank you very much @PortableStick. Nice explanation. :slightly_smiling_face: