Please have a look at the following piece of code used to create a Whack a mole game in JS.
there is a specific line where it shows: hitPosition = randomPositon.id but hitPosition is never ever declared beforehand and the code works perfectly fine without issues. My first question is how come the code work without throwing an error like "hitPosition is not defined" My second question is at the function moveMole() where the variable timer is created and set to "null" and in the next line it is assigned to a setInterval. I would like to know why it mas created in the first place as "null"? Is it possible to create the variable directly into the setInterval function? Why do we need to do it in 2 steps when only 1 step could work?
const square = document.querySelectorAll(".square")
const mole = document.querySelectorAll(".mole")
const timeLeft = document.querySelector("#time-left")
let score = document.querySelector("#score")
let result = 0;
let currentTime = timeLeft.textContent
function randomSquare(){
square.forEach(className=>{
className.classList.remove("mole")
});
let randomPositon = square[Math.floor(Math.random()*9)]
randomPositon.classList.add("mole")
//assign the id of the randomPosition to hitPosition for us to use later
hitPosition = randomPositon.id
}
square.forEach(item=>{
item.addEventListener("click", ()=>{
if(item.id === hitPosition){
result++;
score.textContent = result
}
})
})
function moveMole(){
let timerId = null;
timerId = setInterval(randomSquare, 1000)
}
moveMole()
function countDown(){
currentTime--
timeLeft.textContent = currentTime
if(currentTime === 0){
clearInterval(timerId);
alert("Game Over! your final sore is: " +" "+result)
}
}
let timerId = setInterval(countDown, 1000)