Yofriadi Yahya
Yofriadi Yahya

Reputation: 13

My function doesn't change value of variable

I don't understand why my code doesn't change it's value

let gameIsRunning = false;

const start = document.getElementById('start-game');
start.addEventListener('click', startGame);

function startGame() {
  return gameIsRunning = true;
}

console.log(gameIsRunning); // still false after click start-game

There is actually slightly more code inside, but I made it shorter.

Upvotes: 0

Views: 250

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

You need first to click on the start-game element. Remove the return part from the function and put the console.log inside the function.

let gameIsRunning = false;

const start = document.getElementById('start-game');
start.addEventListener('click', startGame);

function startGame() {
  gameIsRunning = true;
  console.log(gameIsRunning);
}
<p id="start-game">Click</p>

Upvotes: 2

Related Questions