Hey guys, I just finished up on my latest project and was wondering if I could get any advice to improve my current code. I wouldn’t say my code is bad at all, but I feel like I could do some things to clean it up and improve performance. Ill have a link below to the project.
Great idea for a project, and I love the styling! Overall, it’s really well done.
Here are my suggestions for improving your JS:
The keypress listener on line 172: can you simplify this? You’re doing the same comparison over and over. If you ever want to increase the difficulty of the game (so that an answer might be something other than 1-9) this conditional statement is going to take up too many lines of code. Why not ask if e.which === probAnswer - 48?
Separation of duties: some of your functions are doing a lot of work. Are you familiar with MVC? I won’t go into too much detail, but in this context the idea is that 1 function does math/logical comparisons, 1 function interacts with the DOM, and 1 function triggers other functions to run. Think about your processing() function. It’s doing all three of those things. Try to write smaller functions that just do 1 task. And make sure they have descriptive names - it should be clear from the name what a function will do without having to read the comments.
Can you retain the functionality of the game without using global variables? Unless you absolutely need them, it’s my understanding that they’re not necessary.
I am actually trying to find a way to simplify this repetitive task. I thought of sticking it in a for loop and increasing the number on the conditional by one every time the the input of the keypress does not match the conditional until it does, but that showed a lot of problems. A switch statement would make the problem just as long. For now, I condensed the 10 if statements into 1 by using the | | operator and am currently looking at this solution on stack overflow and thinking of how I can adjust it for my problem. http://stackoverflow.com/questions/20420856/dry-how-to-exchange-this-if-statement-into-less-complex
Yeah, it worked that way. I never thought about subtracting the key code by a hard coded number to match the user’s answer to the problem. Thanks, I will take this idea into account for similar problems that will occur in the future.