Javascript oneliners: functions are attributes too

Richard

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:

1
2
3
4
5
6
7
var someClass = 'some-class';
var hasClass = element.hasClass(someClass);
if(hasClass){
element.addClass(someClass);
} else {
element.removeClass(someClass);
}

but we could also write

1
2
3
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.

ngImprovedTesting: mock testing for AngularJS made easy ngEurope: about AngularJS 1.3, new router and the future 2.0