OK, first the obvious solution with if/else-statements:
var c = b.clone();
if ( b.data("letter") == target.data("letter") ) {
c.addClass("wordglow3");
hit.play();
} else {
c.addClass("wordglow");
miss.play();
}
c.appendTo(table).css(…);
Now, we could remove some duplicate code using variables:
var className, sound;
if ( b.data("letter") == target.data("letter") ) {
className = "wordglow3";
sound = hit;
} else {
className = "wordglow";
sound = miss;
}
b.clone().addClass(className).appendTo(table).css(…);
sound.play();
or even shorter by initialising them with the defaults:
var className, = "wordglow",
sound = miss;
if ( b.data("letter") == target.data("letter") ) {
className += "";
sound = hit;
}
…
Using the ternary operator gets harder. We could use the comma operator to chain different actions in the same expression:
b.clone().addClass( b.data("letter") == target.data("letter")
? hit.play(), "wordglow3"
: miss.play(), "wordglow"
).appendTo(table).css(…);
But this is ugly. A better choice would be using a variable for the condition and two ternary operators:
var success = b.data("letter") == target.data("letter");
b.clone().addClass(success ? "wordglow3" : "wordglow").appendTo(table).css(…);
(success ? hit : miss).play();
Once we've got here, you even might consider an extra data structure for your sounds and class names, to replace millions of (especially nested) if-statements with selection by key:
// global:
var sounds = { // or use an arrays
"0": …, // miss
"1": … // hit
};
var classes = {
"0": "wordglow",
"1": "wordglow3"
};
// […]
// then, select values by casting the boolean to numeric keys:
var success = b.data("letter") == target.data("letter");
b.clone().addClass(classes[+success]).appendTo(table).css(…);
sounds[+success].play();
This makes extending your application with other cases easy, and allows an easier maintenance of used class names or sounds (in a central place) if they are used like this everywhere. Also, we've reduced two variables hit
and miss
to only one sounds
.
Decide yourself which code snippet is best readable or most appropriate in your situation.