Global Variables in JavaScript

javascript_featured

In many scenarios JavaScript coders find themselves in a need to store a value in a variable located inside a function to be later called by another function.

One interesting way of doing so is to actually attach the variable to the window object as follows:

function setValue()
{
    window.myVar = "test";
}

function getValue()
{
    alert(window.myVar); //this will output "test" given setValue() runs first
}

How easy is that?!

In fact when a global variable is set, it’s automatically added to the window object!

There is another way available for those using the jQuery library and that is to create a namespace inside the jQuery object or function, like so:

function setValue()
{
$.mynamespace = { 
    myVar : "test", 
};
}

function getValue()
{
    alert($.mynamespace.myVar); //this will output "test" given setValue() runs first
}

or this could be rewritten as follows:

function setValue()
{
$.mynamespace = {};
$.mynamespace.myVar = "test";
}

function getValue()
{
    alert($.mynamespace.myVar); //this will output "test" given setValue() runs first
}

If you have any questions or would like me to discuss a certain topic please send me a message or simply just leave a comment below!

Global Variables in JavaScript
4 votes, 4.25 avg. rating (84% score)
  • Posted in: JavaScript & jQuery
Husamaldin Tayeh

Posted by

Husamaldin is a computer programmer, blogger, entrepreneur and an overall thinker. He is the founder and editor of Coders Mount. He loves everything about computers and programming. Find out more about him here or follow him on Twitter Google+ | LinkedIn.