144

How can I declare a global variable in JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dancer
  • 17,035
  • 38
  • 129
  • 206

6 Answers6

226

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

Servy
  • 202,030
  • 26
  • 332
  • 449
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    `window` is available only in browsers. Could you edit you answer to make it work in all environments? See [How to get the global object in JavaScript?](http://stackoverflow.com/q/3277182/3853934) – Michał Perłakowski Nov 30 '16 at 15:50
  • The `global` object in node.js is the same as the `window` object in browsers – GiantBooley Mar 17 '22 at 23:55
52

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
  • Thanks for that Tomas, In the site I mentioned above Felix approach works fine, but i have another site I'm also working on that uses several plugins and your approach would be ideal if i can get it to work. Cheers for your help. – Dancer Jul 28 '10 at 11:16
  • This works perfectly well! Just make sure as @Tomas says, Make your own class/holder for your own custom functions or variables. +1 – Pierre Jan 21 '15 at 07:52
  • Thanks Tomas! If no more required, delete parent object (e.g.: `delete $.miniMenu` ). Is it OK? – Kunj Mar 02 '15 at 06:00
  • 1
    @KunJ: Sure, as with anything: if you can guarantee that it won't be used anymore, it's safe to delete it. However, JavaScript will garbage collect it for you, so you don't *have* to `delete $.miniMenu`. – Tomas Aschan Mar 02 '15 at 14:42
20

Note: The question is about JavaScript, and this answer is about jQuery, which is wrong. This is an old answer, from times when jQuery was widespread.

Instead, I recommend understanding scopes and closures in JavaScript.

Old, bad answer

With jQuery you can just do this, no matter where the declaration is:

$my_global_var = 'my value';

And will be available everywhere.

I use it for making quick image galleries, when images are spread in different places, like so:

$gallery = $('img');
$current = 0;

$gallery.each(function(i,v){
    // preload images
    (new Image()).src = v;
});
$('div').eq(0).append('<a style="display:inline-block" class="prev">prev</a> <div id="gallery"></div> <a style="display:inline-block" class="next">next</a>');
$('.next').click(function(){
    $current = ( $current == $gallery.length - 1 ) ? 0 : $current + 1;
    $('#gallery').hide().html($gallery[$current]).fadeIn();
});
$('.prev').click(function(){
    $current = ( $current == 0 ) ? $gallery.length - 1 : $current - 1;
    $('#gallery').hide().html($gallery[$current]).fadeIn();
});

Tip: run this whole code in the console in this page ;-)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aesede
  • 5,541
  • 2
  • 35
  • 33
  • 3
    Aren't $gallery and $current just normal global variables? They work because you are defining them as global variables by omitting 'var', but the dollar sign in front of them don't make them 'jQuery variables'... It's literally as putting an underscore or any other sign on from of them... They would be jQuery variables if you use the jQuery object ($) and add a property to it: $.myGlobalVariable = 'my value'... – Andres Elizondo Aug 16 '17 at 13:09
  • You're probably right, but what is worth noticing is that using $myVar syntax you get 2 adventages, 1) variable is global without any special declarations (besides the $); and 2) you can track your global variables very easily inside the code. Open to discussion though... – aesede Aug 16 '17 at 14:26
  • A misled answer. Agree with Andres, that is NOT a jQuery variable at all. If you don't define `$current = 0;` at the beginning out of the function, the later one won't work. – harrrrrrry Jul 17 '19 at 18:15
15

Here is a basic example of a global variable that the rest of your functions can access. Here is a live example for you: http://jsfiddle.net/fxCE9/

var myVariable = 'Hello';
alert('value: ' + myVariable);
myFunction1();
alert('value: ' + myVariable);
myFunction2();
alert('value: ' + myVariable);


function myFunction1() {
    myVariable = 'Hello 1';
}

function myFunction2() {
    myVariable = 'Hello 2';
}

If you are doing this within a jQuery ready() function then make sure your variable is inside the ready() function along with your other functions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Dragoonis
  • 2,315
  • 1
  • 16
  • 22
  • Best answer for how global variables work in jQuery yet. – Clinton Green Mar 04 '16 at 22:52
  • 1
    I know I'm grave digging but this is not even an explicit global variable. This is a more in tune with a shared public variable not scoped into a closure for extremely small scripts. They are two entirely different methods/usages and this one will get you in major trouble if your declaring an explicit global in a script that is in the middle of several different scripts. I can only imagine a front end on my team declaring a global variable at the top of a script that is the 10th one being called into the DOM. – Brian Ellis Mar 28 '16 at 20:19
4

Declare the variable outside of functions

function dosomething(){
  var i = 0; // Can only be used inside function
}

var i = '';
function dosomething(){
  i = 0; // Can be used inside and outside the function
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3632465
  • 63
  • 1
  • 7
4

The best way is to use closures, because the window object gets very, very cluttered with properties.

HTML

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>
</html>

init.js (based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // Private

    return {
        init : function(Args) {
            _args = Args;
            // Some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

robe007
  • 3,523
  • 4
  • 33
  • 59