HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Writing a set of JavaScript conditionals more efficiently

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
efficientlyconditionalsjavascriptwritingmoreset

Problem

There must be a better way to write this, maybe with a switch statement (which for some reason I can't get to work). Basically, if one of the conditionals is true then the class in the statement is executed. So, in this case, one or any number of combinations could be true.

if (stepOneEdited) {
    $(stepOne).addClass("complete");
}
if (stepTwoEdited) {
    $(stepTwo).addClass("complete");
}
if (stepThreeEdited) {
    $(stepThree).addClass("complete");
}
if (stepFourEdited) {
    $(stepFour).addClass("complete");
if (stepFiveEdited) {
    $(stepFive).addClass("complete");
    $(stepSix).addClass("complete");
}

Solution

I like @janos solution, but if that is not possible for you, you might extract the code into a function. I know, it's just one line of code, but I think it would still be beneficial:

// marks className element as complete if isEdit is true
function addComplete(isEdit, className) {
    if (isEdit) {
        $(className).addClass("complete");
    }
}

addComplete(stepOneEdited, stepOne);
addComplete(stepTwoEdited, stepTwo);
addComplete(stepThreeEdited, stepThree);
addComplete(stepFourEdited, stepFour);
addComplete(stepFiveEdited, stepFive);
// stepSix depends on stepFiveEdited, not stepSixEdited
addComplete(stepFiveEdited, stepSix);


This way, each additional step only takes one line instead of three, I think that this makes it a lot more readable (and also adding a new case is a lot easier). The other benefit is that it is easier to adapt this code if the specification changes. For example if the class name changes, or if instead of adding a class, the program should react differently, you only need to change it in one place.

Code Snippets

// marks className element as complete if isEdit is true
function addComplete(isEdit, className) {
    if (isEdit) {
        $(className).addClass("complete");
    }
}

addComplete(stepOneEdited, stepOne);
addComplete(stepTwoEdited, stepTwo);
addComplete(stepThreeEdited, stepThree);
addComplete(stepFourEdited, stepFour);
addComplete(stepFiveEdited, stepFive);
// stepSix depends on stepFiveEdited, not stepSixEdited
addComplete(stepFiveEdited, stepSix);

Context

StackExchange Code Review Q#60902, answer score: 4

Revisions (0)

No revisions yet.