0

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)
user229044
  • 232,980
  • 40
  • 330
  • 338
Tesa
  • 47
  • 4
  • 1
    Your question should include the shortest amount of code necessary to reproduce the problem. In this case, you can reduce your code to `x = 1`, and ask why `x` does not have to be declared. – user229044 Jul 11 '20 at 00:41
  • regarding your second question: You can directly assign any value to a variable without declaring it beforehand. Also, You can simply return `setInterval(randomSquare, 1000)` from the function as variable declared with let aren't accessible outside of its scope which is `function moveMole` in this case – Basheer Kharoti Jul 11 '20 at 00:49

0 Answers0