I am currently adding extra sounds to my game. The problem is I have a shorthand if statement like “?…:…” and don’t know how I can add audio to it. If it is not possible how would I make it a normal if statement without making it crash.
b.clone().addClass(
b.data("letter") == target.data("letter") ? "wordglow3" : "wordglow").appendTo("table").css({
background: "transparent",
position: "absolute",
top: currentPos.top,
left: currentPos.left
})
So if “wordglow3” I want to add “hit.play()” and for “wordglow” I want to add “miss.play()”
OK, first the obvious solution with if/else-statements:
Now, we could remove some duplicate code using variables:
or even shorter by initialising them with the defaults:
Using the ternary operator gets harder. We could use the comma operator to chain different actions in the same expression:
But this is ugly. A better choice would be using a variable for the condition and two ternary operators:
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:
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
hitandmissto only onesounds.Decide yourself which code snippet is best readable or most appropriate in your situation.