Javascript oneliners: functions are attributes too

by Richard — 1 minutes

Just a small reminder. Javascript allows you to call methods based on their name. So if a DOM element has a addClass and removeClass which both take the same argument we could write:

var someClass = "some-class";
var hasClass = element.hasClass(someClass);
if (hasClass) {
  element.addClass(someClass);
} else {
  element.removeClass(someClass);
}

but we could also write

var someClass = "some-class";
var hasClass = element.hasClass(someClass);
element[hasClass ? "addClass" : "removeClass"](someClass);

Sometimes this means you can use this technique to write powerful one liners.

meerdivotion

Cases

Blogs

Event