Home > Back-end >  Variable throws initialization error after initializing it
Variable throws initialization error after initializing it

Time:10-23

I'm trying to make a Discord bot, one of its features is that it plays chess, at the start of the command, I read the JSON file, then check if it's undefined since I'll call a key from the object, so just in case it doesn't exist already, I'll create the data needed

Problem is, when I try to assign the data, it says I haven't initialized the variable, which is weird, because I did initialize it 3 lines before, var, let and const all throw the same error

Another thing is that outside the if statement, just above it, when console.logging it, it works perfectly, but when console.logging it inside the if statement, it throws that error

I honestly have no idea what's happening here, I can't think of anything that's causing this either, is this a NodeJS bug? I feel like it could be.

const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json"))
console.log(games, 'outside if statement') // Here it outputs just fine
if (games[interaction.guild.id] == undefined) {
    console.log(games, 'inside if statement') // Here is where it breaks
    games[interaction.guild.id] = {
        games: {},
        players: {},
        amount_of_games: 0
    }
    fs.writeFileSync("./lib/database/games/chess/chess_games.json", JSON.stringify(games, null, 2));
    const games = JSON.parse(fs.readFileSync("./lib/database/games/chess/chess_games.json"))
}

This is the error:

ReferenceError: Cannot access 'games' before initialization
    at Object.execute (C:\Users\aschr\Dropbox\Coding\Javascript\entropic_bot\lib\database\bot\commands\chess.js:40:4)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Client.<anonymous> (C:\Users\aschr\Dropbox\Coding\Javascript\entropic_bot\index.js:44:3)

CodePudding user response:

You have two variables with the same name.

Change the name of one of them

The second games is tried to be accessed instead of the first one because of hoisting. That's why you are getting the error

  • Related