Often when using jQuery and you aim to add or remove a class based on a state variable, you will see a function such as.
function updateInterface () {
var shouldShowLogout = user.isLoggedIn;
if (shouldShowLogout)
$('.logout-button').addClass('active');
} else {
$('.logout-button').removeClass('active');
}
}
This function is hard to read and basically repeats itself in the if and else clauses. The function implementation can be refactored down to 2 lines using a ternary if operator.
function updateInterface () {
var shouldShowLogout = user.isLoggedIn;
$('.logout-button')[ shouldShowLogout ? 'addClass' : 'removeClass' ]('active');
}
Since you can access functions of a an object in JavaScript like values, you can use the []
accessor to return the correct function based on the ternary if statement and them immediately call it using ()
, or in this case passing our class name value ('active')
.
You could even take this down to a single line.
function updateInterface () {
$('.logout-button')[ user.isLoggedIn ? 'addClass' : 'removeClass' ]('active');
}
Although this final single line approach may be confusing to the next developer who is not already familiar with the pattern.