Ask coding questions

← Back to all posts
Getting 'variable is not defined at client' error
AkonZ

I am trying to access a variable I declared however I am getting undefined. I declared the variable using the 'var' keyword in an if-statement(for a discord bot command) and tried accessing its value in another if-statement but that is not working, anyone could know whats the problem ? A similar example to my problem could be shown here: [NodeJS]
if (command == 'bla'){
var number = 7;
}
if (command == 'vla'){
var newNumber = number + 2;
message.channel.send(newNumber)
}

Voters
AkonZ
Comments
hotnewtop
heyitsmarcus

You need to declare the variable number outside of the entire event loop. But, even besides that, you are declaring a new variable inside of the if statement. Keep in mind that, in JavaScript (browser or Node), var variables are function based, meaning that any var variable created from within a function will disappear when that function is finally executed. And let and const have their own block level scopes, as well.

What you really want to do is create your number variable way above the listener for a message in the global scope so that it can hold its value.

Dive into FreeCodeCamp.org's courses (https://freecodecamp.org) and go through their JavaScript course. It would benefit you greatly.

AkonZ

@heyitsmarcus Hello Marcus, thank you for your reply. Actually I am full aware of the scopes and I already tried your approach. It didnt work. I would get the value 0 for number and not 7 when using the command 'vla'. The reason is that the bla command is not being fulfilled therefore the variable is not getting updated. I found a temporary fix which is to use the command 'bla' and right after it use the command 'vla' (in the discord server of course) , only then will the value of number be 7 because the if statement for 'bla' got fulfilled. I want to find a way to make the value of number = 7 without having to use the first command before the second command as it would be inconvenient for my discord users. Let me know if you have a fix for the problem!

heyitsmarcus

@AkonZ I am going off of the sparse code you posted. Post your Repl and maybe we can help you further. But my explanation is correct. I don't even know what your goal is because you didn't fully explain it. This is a poor excuse of asking a question on Replit.