Max Williams
Max Williams

Reputation: 32945

Is this jQuery pattern browser-safe: "attr('foo') || 'default'"?

This seems like a neat way to read a value from a data attribute or use a default value if it's not present:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text") || "Delete this resource?";

It relies on undefined (which is returned if the attribute isn't present) being falsey. Is this a browser-safe solution? If not, what's a nicer way?

Upvotes: 2

Views: 36

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

Yes it's browser safe. Just be wary of using it on values which are falsy when valid, eg 0, or false. Also note that you'll find some people who don't like using that construct, but that's mostly for code readability issues, not browser support.

The alternatives are an if statement:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text");
if (!confirmMessage)
  confirmMessage = "Delete this resource?";

Or a ternary:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text") ? resourceDiv.attr("data-confirm-delete-text") : 'Delete this resource?';

As you can see, they are much more verbose, and in the case of the ternary, may include some redundancy.

Upvotes: 2

Related Questions