I am using JavaScript and I create a global variable. I define it outside of a function and I want to change the global variable value from inside a function and use it from another function, how do I do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Just reference the variable inside the function; no magic, just use it’s name. If it’s been created globally, then you’ll be updating the global variable.
You can override this behaviour by declaring it locally using
var, but if you don’t usevar, then a variable name used in a function will be global if that variable has been declared globally.That’s why it’s considered best practice to always declare your variables explicitly with
var. Because if you forget it, you can start messing with globals by accident. It’s an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.