Austin Griner
Austin Griner

Reputation: 185

Combine if/else into one statement? (Javascript)

function changeButton () {
    if (event.currentTarget.className == 'btnRed') {
        event.currentTarget.className = 'btnGreen';
    } else {
        event.currentTarget.className = 'btnRed';
    }
}

Let's say I have the above code. I have seen similar codes written that would combine these two, but I don't really remember how it did it. It was something like className = (btnGreen | btnRed).
I am very sorry for the vagueness of this question.

Upvotes: 2

Views: 184

Answers (1)

Callum Linington
Callum Linington

Reputation: 14417

You can use the ternary operator (condition) ? (true) : (false)

event.currentTarget.className = event.currentTarget.className == 'btnRed' ? 'btnGreen' : 'btnRed';

I would go a little bit further, extract the strings into variables to remove the ability to mistype them across the solution. And refactor event.currentTarget into a variable.

var RED_BUTTON_CLASS = 'btnRed', 
    GREEN_BUTTON_CLASS = 'btnGreen';

var currentTarget = event.currentTarget;

currentTarget.className = currentTarget.className == RED_BUTTON_CLASS ? GREEN_BUTTON_CLASS : RED_BUTTON_CLASS;

This I feel will just make it easier in the long run, completely optional

Edit

So adding extra information from what Jan said.

var RED_BUTTON_CLASS = 'btnRed', 
    GREEN_BUTTON_CLASS = 'btnGreen';

These probably describe a state, so you could better name them:

var ERROR_BUTTON_CLASS = 'btnRed', 
    OK_BUTTON_CLASS = 'btnGreen';

Upvotes: 4

Related Questions