How do I create a global variable with Javascript?

Global Variable vs. Local Variable

Global variable means the data it holds can be referenced from anywhere in the document, whereas local means the variable data can only be referenced from inside the function it was created in.

The Short Answer

Move the variable declaration outside of your function and add the word “var” in front of it.

var a = "Global Variable";
displayVariable();
function displayVariable()
   {
   var a = "Local Variable";
   alert(a);
   }
alert(a);

In executing this code you’ll see that the variable “a” contains two separate values “Global Variable” and “Local Variable”. The alert function in displayVariable will display the local variable first, if it doesn’t find it then it will check for the global variable.

So if your code is written properly but Javascript still won’t recognize your variable it’s possible that you need a global declaration, happy coding!

Back to Blog

Say Hello

You can reach me by email, I'd love to hear from you.