Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Variable inside Module keeps on returning undefined

I want to modify variable currentPlayer each turn. I have added PlayerController.switchPlayer() to an event listener as well. But every time currentPlayer fails to get updated and returns undefined. I even tried moving the same variable to global as an undefined and still it will fail to get updated despite the code running through the whole if/else block.

const PlayerController = (() => {
  let playerO = Player("O");
  let playerX = Player("X");
  let currentPlayer;
  let switchPlayer = () => {
    if (!playerO.activePlayer) {
      playerO.activePlayer = true;
      playerX.activePlayer = false;
      currentPlayer = playerO;
    } else if (playerO.activePlayer && !playerX.activePlayer) {
      playerX.activePlayer = true;
      playerO.activePlayer = false;
      currentPlayer = playerX;
    }
  };
  return { playerO, playerX, switchPlayer, currentPlayer };
})();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The object to be returned is calculated once - at the end of the IIFE. Calling switchPlayer and reassigning the local currentPlayer does not change the returned object with the currentPlayer property, because the object has already been evaluated and returned.

You could make currentPlayer into a getter instead, so that it returns the possibly-reassigned value inside the IIFE:

return {
  playerO,
  playerX,
  switchPlayer,
  get currentPlayer() {
    return currentPlayer;
  }
};

But I'd prefer to not hide the fact that it's a function, so that you call getCurrentPlayer from the outside.

return {
  playerO,
  playerX,
  switchPlayer,
  getCurrentPlayer: () => currentPlayer
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!