If/Else nightmare. jQuery Optimization tips?
I have the following (example) jQuery code within a function that as you can see contains some awful if/else statements with a lot of repetition of sorts. Is there a better (more performance, DRY, readable) way of going about all these if/else statements?
I'm not trying to just concatenate the different options either, the result of each if will be very different in each case.
var qux = "";
if (foo == 'a') {
if (bar == 'x') {
if (baz == 'm') {
qux = $('#div').html('result 1');
} else if (baz == 'n') {
qux = $('#div').html('result 2');
}
} else if (bar == 'y') {
if (baz == 'm') {
qux = $('#div').html('result 3');
} else if (baz == 'n') {
qux = $('#div').html('result 4');
}
} else if (bar == 'z') {
if (baz == 'm') {
qux = $('#div').html('result 5');
} else if (baz == 'n') {
qux = $('#div').html('result 6');
}
}
} else if (foo == 'b') {
if (bar == 'x') {
if (baz == 'm') {
qux = $('#div').html('result 7');
} else if (baz == 'n') {
qux = $('#div').html('result 8');
}
} else if (bar == 'y') {
if (baz == 'm') {
qux = $('#div').html('result 9');
} else if (baz == 'n') {
qux = $('#div').html('result 10');
}
} else if (bar == 'z') {
if (baz == 'm') {
qux = $('#div').html('result 11');
} else if (baz == 'n') {
qux = $('#div').html('result 12');
}
}
} else if (foo == 'c') {
if (bar == 'x') {
if (baz == 'm') {
qux = $('#div').html('result 13');
} else if (baz == 'n') {
qux = $('#div').html('result 14');
}
} else if (bar == 'y') {
if (baz == 'm') {
qux = $('#div').html('result 15');
} else if (baz == 'n') {
qux = $('#div').html('result 16');
}
} else if (bar == 'z') {
if (baz == 'm') {
qux = $('#div').html('result 17');
} else if (baz == 'n') {
qux = $('#div').html('result 18');
}
}
}
EDIT: Changed code for clarification.
Answers 1
Two different options I'd consider to neaten up your code are as follows:
A small change: given that every single case does
$("#div").html('result xx')
, just set:and then after the if/else structure say:
At least that way you're not having to repeat the
$("#div").html()
part everywhere. It would still be a giant, uglyif/else
structure, but this option might make sense if your real-world code has more complicated combinations of test conditions that can't easily be combined.Given that the
if/else
example you show is based on various combinations of the same three variables' values, you can replace the structure with a lookup table, perhaps something like the following:Either way you might consider encapsulating the calculation in a function, so that it doesn't clutter up the code around it, leaving a call something like:
(Note: I don't understand why you would initialise
qux
as an empty string and then in the if/else structure set it to the return value from.html('some result')
, because that return value would be a jQuery element which doesn't seem like a sensible alternative to a string, but anyway...do or don't include code for that as required.)