Question regarding variable instantiation and usage

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:

I have two questions about this:

  1. 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?
  2. 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?

Separate declarations in separate scopes are completely separate and have nothing to do with each other.

No clue why they didn’t declare and properly instantiate at the same item.

I had a feeling it was scope. If that’s the case, how would I clearInterval of the timerId in moveMole?

You would do it inside of that scope.

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.