Define a global variable in a JavaScript function

As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:

<script>
var yourGlobalVariable;
function foo() {
    // ...
}
</script>

(Note that that’s only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn’t be at global scope, so that wouldn’t create a global.)

Alternatively:

In modern environments, you can assign to a property on the object that globalThis refers to (globalThis was added in ES2020):

<script>
function foo() {
    globalThis.yourGlobalVariable = ...;
}
</script>

On browsers, you can do the same thing with the global called window:

<script>
function foo() {
    window.yourGlobalVariable = ...;
}
</script>

…because in browsers, all global variables global variables declared with var are properties of the window object. (In the latest specification, ECMAScript 2015, the new letconst, and class statements at global scope create globals that aren’t properties of the global object; a new concept in ES2015.)

(There’s also the horror of implicit globals, but don’t do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5’s "use strict".)

All that said: I’d avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, in modern environments, use modules:

<script type="module">
let yourVariable = 42;
// ...
</script>

The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn’t global.

In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
    var yourGlobalVariable; // Global to your code, invisible outside the scoping function
    function foo() {
        // ...
    }
})();         // End scoping function
</script>

Leave a Comment