I was following along on the Learn JavaScript by Building 7 Games - Full Course video on youtube. On the second game, ‘Whack A Mole’, there is this snippet of code:
Why does she use ‘timerId’ as a variable name twice? Are they related, since they both set-up a setInterval? Why does clearInterval(timerId) only stop one of them and not the other?
Why does she initially instantiate the top timerId as ‘null’? I know what ‘null’ is, but why not just set it to setInterval, instead of setting it to ‘null’ before changing it?
The only thing that comes to mind is that if there was some error that occurred with setInterval(randomSquare, 1000), then timerId would exist with the value of null rather than being undefined, and that may be handled more gracefully.
If this is from a YouTube video it may also be either that
a) they were walking through things step by step, so they created the variable before giving it a meaningful value.
b) this is an artifact of real-time coding and something that would have been tidied up in refactoring at the end in a “real” situation.