Search code examples
javascripthtmlundefinedtic-tac-toeuncaught-reference-error

How do I fix an uncaught reference error for this TicTacToe


I am doing a HTML, CSS, JSS tictactoe project, and I have run into an error where the console ribbon/section (when right clicking and going to "inspect" in browser) has stated the following when I tried using the console.log in my text editor:


"Uncaught ReferenceError: topLeft is not defined"
if (topLeft && topLeft === topMiddle && topLeft === topRight) {

my code:

             // HTML Elements
const statusDiv = document.querySelector('.status');
const resetDiv = document.querySelector('.reset');
const cellDivs = document.querySelectorAll('.game-cell');
//NEW querySelecterAll <= will grab every occurrence put in ('') 
//Grabbing statusDiv to manipulate it (change when it'll x or o's turn)

            //Game Variables
let gameIsLive = true; 
//statement would be false if someone won/ game ended 
let xIsNext = true; 
//meaning if it's T = x's turn, if it's F = O's turn

           // Functions
const checkGameStatus = () => {
const topLeft = cellDivs[0].classList[2];
const topMiddle = cellDivs[1].classList[2];
const topRight = cellDivs[2].classList[2];
const middleLeft = cellDivs[3].classList[2];
const middleMiddle = cellDivs[4].classList[2];
const middleRight = cellDivs[5].classList[2];
const bottomLeft = cellDivs[6].classList[2];
const bottomMiddle = cellDivs[7].classList[2];
const bottomRight = cellDivs[8].classList[2];
}

           // Check Winner
if (topLeft && topLeft === topMiddle && topLeft === topRight) { 
console.log(topLeft);
}

The code I have done seems to be the same as the video, so I'm unsure as to why I'm receiving this error.

References

  • GitHub

The person in the tutorial has his own GitHub with the code enter link description here

  • Youtube

This will be where I currently am with the process enter link description here

I posted a similar question before and it was my first time getting a question closed. A bit worried that it might get closed again so if please let me know what part in my question that I did wrong.


Solution

  • Your issue is with block scoping. You're declaring your variables inside this block:

    const checkGameStatus = () => {
      const topLeft = cellDivs[0].classList[2];
      [...]
    }
    

    But then you're trying to access the variables outside the block, where they don't exist.

    Instead, initialize the variables outside the block, and then assign the values:

    let topLeft;
    
    const checkGameStatus = () => {
      topLeft = cellDivs[0].classList[2];
      [...]
    }
    
    checkGameStatus()
    
    if (topLeft && topLeft === topMiddle && topLeft === topRight) { 
      console.log(topLeft);
    }