662

Is it possible to define a global variable in a JavaScript function?

I want use the trailimage variable (declared in the makeObj function) in other functions.

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
        <script type="text/javascript">
            var offsetfrommouse = [10, -20];
            var displayduration = 0;
            var obj_selected = 0;
            function makeObj(address) {
                **var trailimage = [address, 50, 50];**
                document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0"  style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
                obj_selected = 1;
            }

            function truebody() {
                return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
            }
            function hidetrail() {
                var x = document.getElementById("trailimageid").style;
                x.visibility = "hidden";
                document.onmousemove = "";
            }
            function followmouse(e) {
                var xcoord = offsetfrommouse[0];
                var ycoord = offsetfrommouse[1];
                var x = document.getElementById("trailimageid").style;
                if (typeof e != "undefined") {
                    xcoord += e.pageX;
                    ycoord += e.pageY;
                }
                else if (typeof window.event != "undefined") {
                    xcoord += truebody().scrollLeft + event.clientX;
                    ycoord += truebody().scrollTop + event.clientY;
                }
                var docwidth = 1395;
                var docheight = 676;
                if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
                    x.display = "none";
                    alert("inja");
                }
                else
                    x.display = "";
                x.left = xcoord + "px";
                x.top = ycoord + "px";
            }

            if (obj_selected = 1) {
                alert("obj_selected = true");
                document.onmousemove = followmouse;
                if (displayduration > 0)
                    setTimeout("hidetrail()", displayduration * 1000);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px;
            top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
        </form>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hamze
  • 7,061
  • 6
  • 34
  • 43
  • 28
    to declare a global simply don't use the "var" keyword – Ibu Apr 26 '11 at 06:46
  • 26
    @Ibrahim: *"to declare a global simply don't use the "var" keyword"* Gak! [The Horror](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html)! ;-) Thankfully, strict mode does away with implicit globals. – T.J. Crowder Apr 26 '11 at 07:22
  • 35
    @Ibrahim Diallo - not using `var` doesn't *declare* a global variable. A consequence of assigning a value to an undeclared variable is the creation of a property on the global object, which is quite different to declaring a variable. – RobG Apr 26 '11 at 07:34
  • 3
    useful info in this answer, too http://stackoverflow.com/a/4862268/1356098 :) – Erenor Paz Nov 26 '12 at 15:35

17 Answers17

917

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. (The new let, const, and class statements [added in ES2015] 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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 11
    Note that using `window` won't work in Node. The easiest trick here is to set: `GLOBAL.window = GLOBAL;` -- as explained [in this related question](http://stackoverflow.com/a/9590297/2228771). Of course, it's not pretty conceptually. I prefer to do things the other way around, so I can use `GLOBAL` instead of `window`. – Domi Apr 05 '14 at 21:58
  • 4
    @CasparKleijne, I don't understand it. Why would you assign it on window when you literally have no evidence that the window object actually exists. You know nothing about how your code will be used in the future. It might be even used in the MongoDB environment or rino instead of your node. And the window object is also not visible even in the browser if you use web workers for instance. This will completely kill reusability. – Gherman Feb 10 '16 at 11:36
  • 6
    `window.yourGlobalVariable = ...;` works like a charm after reading 5 to 6 questions on stack site. – Ahmed Syed Feb 16 '16 at 12:25
  • You can also set dynamic variables in the window by using code like this: `eval("window."+dynamic_variable_name+" = '"+dynamic_variable_value+"';");` which is helpful if you need to maintain the value of custom JS/HTML elements – Jacques Koekemoer Mar 10 '16 at 09:57
  • 6
    @JacquesKoekemoer: There's no reason whatsoever to use `eval` there. Instead: `window[dynamic_variable_name] = dynamic_variable_value;` – T.J. Crowder Mar 10 '16 at 10:05
  • how use the function's trick if you have to import your file in an another file? – Webwoman Mar 05 '19 at 15:52
  • @Webwoman - Import how? JavaScript standard modules? CommonJS? – T.J. Crowder Mar 05 '19 at 16:00
  • like following, module.exports... then require("/") – Webwoman Mar 05 '19 at 16:06
  • @Webwoman - (CommonJS) There's no need for it. In a CommonJS-style module (such as Node.js's modules), your top-level code isn't at global scope, so `var x;` won't create a global. (But if you wanted to do it anyway, you'd just assign to `module.exports` within the wrapper function. `(function() { var moduleGlobal = 42; module.exports.foo = function foo() { /*...*/ }; })()`) – T.J. Crowder Mar 05 '19 at 16:20
  • I think this is another way too: (() => { a = 10; console.log(a); })(); console.log(a); – Astrit Spanca Feb 20 '20 at 01:20
  • 1
    @AstritSpanca - That's the [Horror of Implicit Globals](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) I mention in a parenthetical in the middle of the answer. :-) – T.J. Crowder Feb 20 '20 at 09:16
  • @T.J.Crowder i am well aware of it though i didn't notice that in your answer. Anyway using global variables is uneccessary most of the time. – Astrit Spanca Feb 20 '20 at 10:51
  • @AstritSpanca - Indeed. And it's *never* necessary (anymore) to use implicit globals. :-) – T.J. Crowder Feb 20 '20 at 11:07
  • I had to define `window.yourGlobalVariable = ...;` outside of `function foo()` to make the variable accessible. Is "global variables declared with var are properties of the window object" still valid? – Avatar Oct 27 '20 at 11:19
  • 1
    @KaiNoack - Yes, it is. My guess is that you were using a module. The top-level scope of modules isn't global scope, so `var` there doesn't create a global variable, just a variable that's global to the module. – T.J. Crowder Oct 27 '20 at 11:28
  • Yes, I tried to access the global variable from within a module/plugin, in the callback function. And this was undefined. Maybe we should add this special case to the answer? – Avatar Oct 27 '20 at 14:44
  • 1
    @KaiNoack - The answer needed miscellanous updating and cleanup, so I've done that and mentioned modules (and `globalThis`). :-) – T.J. Crowder Oct 27 '20 at 14:59
  • I'm reading this post because I'm trying to understand why I have access to `const actx = "value` declared in a file with `type = "module"` from within a file that has no type defined. `const actx` is an audio context. Both files are loaded in the same app of course, but I didn't expect that behavior and I can't quite see the answer in this post. Could you please explain this further? – Fishbite May 01 '22 at 19:41
  • @Fishbite - You're right to wonder about that because on the face of it, you shouldn't have access to that module-level const from a script (no `type`). I can only think of three possibilities: 1. You have an element in the DOM with `id="actx"` (which creates an automatic global), and it's that global (not the `actx` module const) that you're seeing in your script; or 2. You have a different `actx` global variable declared globally some other way somewhere; or 3. You're using a bundler that's messing this up (which seems unlikely, but...). :-) – T.J. Crowder May 02 '22 at 07:09
  • @Fishbite - If it's not one of those and you can create an [mre], you might post it as a question. Please ping me here with the link if you do. Happy coding! – T.J. Crowder May 02 '22 at 07:10
  • @T.J.Crowder my apologies, I had it back to front. `const actx = new AudioContext():` is declared in a file `script.js` at root level with no type defined and I have access to that context from within a file `playMusic.js` with `type="module"` I have no DOM element with an `id=actx` and I'm not using a bundler. `script.js` is loaded before `playMusic.js` As for posting a question, to reproduce having two files, I would just need to include the contents of each file in a separate code block ```Contents of file 1``` and then ```Contents of file 2``` is that correct? My IDE is VS Code. – Fishbite May 02 '22 at 10:21
  • 1
    @Fishbite - That way around it makes perfect sense. The top level of a non-module script is global, so any top-level declarations are globals, accessible from anywhere. – T.J. Crowder May 02 '22 at 10:51
  • 1
    @T.J.Crowder Phew! I thought I was losing the plot, this has been a great help and my code is working as intended thankfully. I thought I had come across an anomaly. – Fishbite May 02 '22 at 11:17
  • The best: globalThis (in my humble opinion) – Alex8752 Nov 17 '22 at 18:51
31

Just declare

var trialImage;

outside. Then

function makeObj(address) {
    trialImage = [address, 50, 50];
    ...
    ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
harihb
  • 602
  • 2
  • 8
  • 17
22

If you read the comments there's a nice discussion around this particular naming convention.

It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.

Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
op1ekun
  • 1,918
  • 19
  • 26
  • 7
    If You want to define your variables elsewhere be sure to understand what hoisting is. Here is a very nice article about it http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting. Good luck! – op1ekun Dec 29 '12 at 10:55
  • 1
    This isn't what `definition` and `declaration` mean in C. Your first line could be either a declaration or a definition (depending on where it is); the second is just an assignment. A declaration just specifies the interpretation of the identifier (ie. `myVar` is an `int`); if the declaration *also* reserves storage, it is a `definition`. This is unrelated to typing; it's part of how compilation units understand references to other compilation units. – EML Jul 26 '14 at 11:20
  • 4
    Even in JS, `var myVar` is called *declaration* (it doesn't need to be typed) and `myVar = 10` an *assignment*. I've heard the term "defintion" for the compound (`var myVar = 10;`). – Bergi Aug 11 '14 at 14:17
  • Just one more comment to add to the discussion :) http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092 – op1ekun Aug 20 '14 at 10:00
  • Following airbnb's javascript guidelines: https://github.com/airbnb/javascript#variables they call it a variable declaration. – op1ekun Sep 09 '14 at 10:10
  • 2
    This doesn't help to answer the question. It should have been a comment, not an answer. – Stuntddude Mar 07 '16 at 17:32
  • 2
    @Stuntddude you're probably right :( I started answering the question and then decided to diverge a bit, and well this is what we've got. Still some ppl still find it useful so I've left it here. Thanks for your feedback! – op1ekun Mar 08 '16 at 09:20
17

Just declare it outside the functions, and assign values inside the functions. Something like:

<script type="text/javascript">
    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage = null ;  // Global variable
    function makeObj(address) {
        trailimage = [address, 50, 50];  // Assign value

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: http://jsfiddle.net/qCrGE/

var globalOne = 3;
testOne();

function testOne()
{
    globalOne += 2;
    alert("globalOne is :" + globalOne );
    globalOne += 1;
}

alert("outside globalOne is: " + globalOne);

testTwo();

function testTwo()
{
    globalTwo = 20;
    alert("globalTwo is " + globalTwo);
    globalTwo += 5;
}

alert("outside globalTwo is:" + globalTwo);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
12

No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:

var trailimage;

function makeObj(address) {
  trailimage = [address, 50, 50];
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    Sorry! "Is it possible to define a global variable in a JavaScript function?" -- "No, you can't" isn't correct, as the first answer shows! – mustafa.0x Nov 17 '13 at 07:29
  • 6
    @mustafa.0x: You are mistaken. You can't *define* a global variable inside a function. You can *implicitly create* a global variable, or create a *window property* inside a function, but you can't define a global variable inside a function. – Guffa Nov 17 '13 at 13:22
  • 1
    With regards to JavaScript in a browser environment, a global variable and a property of `window` are synonymous. Either way, the semantic distinction you're making is clear, so I don't mind un-downvoting. Edit: unable to change my vote, sorry! – mustafa.0x Nov 18 '13 at 19:05
  • 2
    **if you're not using strict** (but why aren't you using strict?), [you actually *can* **declare** and define global vars inside a function](http://stackoverflow.com/a/3352033/274502) by going against all good practices and just not using the `var`, which is what Guffa meant by *implicitly create* (such as @DhruvPathak pointed there, as well). – cregox Feb 25 '17 at 12:48
  • can we use let replace for it? – huykon225 Mar 20 '23 at 04:59
10

There are three types of scope in JavaScript:

  • Global Scope: where the variable is available through the code.
  • Block Scope: where the variable is available inside a certain area like a function.
  • Local Scope: where the variable is available in more certain areas, like an if-statement

If you add Var before the variable name, then its scope is determined where its location is


Example:

var num1 = 18; // Global scope
function fun() {
  var num2 = 20; // Local (Function) Scope
  if (true) {
    var num3 = 22; // Block Scope (within an if-statement)
  }
}

num1 = 18; // Global scope
function fun() {
  num2 = 20; // Global Scope
  if (true) {
    num3 = 22; // Global Scope
  }
}
ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58
Tahseen Alaa
  • 342
  • 4
  • 9
8

It depends on what you intend by the word "global". If you want global scope on a variable for function use (which is what the OP wants) then you should read after the edit. If you want to reuse data from page to page without the use of a server, you should be looking to you use sessionStorage.


Session Storage

    var Global = 'Global';

    function LocalToGlobalVariable() {

        // This creates a local variable.

        var Local = '5';

        // Doing this makes the variable available for one session
        // (a page refresh - it's the session not local)

        sessionStorage.LocalToGlobalVar = Local;

        // It can be named anything as long as the sessionStorage
        // references the local variable.
        // Otherwise it won't work.
        // This refreshes the page to make the variable take
        // effect instead of the last variable set.

        location.reload(false);
    };

    // This calls the variable outside of the function for whatever use you want.

    sessionStorage.LocalToGlobalVar;

I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp. I have needed the same thing for my code and this was a really good idea.


Scope

As of (I believe) 2015, a new "standard" for javascript (if you will) was introduced. This standard introduced many new ideas into javascript, one of them being the implementation of scope.

https://www.w3schools.com/js/js_scope.asp has all the details concerning this idea, but the cliff notes:

const defines a constant.

var has "global" scope.

let has "function" or "block" scope.

Shmack
  • 1,933
  • 2
  • 18
  • 23
  • So far this is the only answer that works at all, but it requires reloading the page and `location.reload(false);` refreshes the page repeatedly. – iyrin Jun 25 '18 at 06:46
  • In my case I replace `sessionStorage` with `localStorage` and this suppress the need to `function LocalToGlobalVariable()`. I am using `localStorage.setItem("xxx", "yyy")` and `localStorage.getItem("xxx")` for setting and getting the variables. – Ozgun Senyuva Jan 08 '22 at 19:31
6

Classic example:

window.foo = 'bar';

A modern, safe example following best practice by using an IIFE:

;(function (root) {
    'use strict'

    root.foo = 'bar';
)(this));

Nowadays, there's also the option of using the WebStorage API:

localStorage.foo = 42;

or

sessionStorage.bar = 21;

Performance-wise, I'm not sure whether it is noticeably slower than storing values in variables.

Widespread browser support as stated on Can I use....

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35
4

It is very simple. Define the trailimage variable outside the function and set its value in the makeObj function. Now you can access its value from anywhere.

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;

function makeObj(address) {
    trailimage = [address, 50, 50];
    ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bharath
  • 797
  • 6
  • 14
  • I was expecting this to work, but it didn't..? `trailimage` was only available as a global entity when not defined anywhere - with or without `var`. – Johan Feb 07 '23 at 10:13
4

Yes, You can. Just don't use var, don't use let. Just initialize variable and it will be automaticly assigned global:

    function firstFunction() {
        if (typeof(testVar) === "undefined") {testVar = 1;} //initializing variable if not initialized
        testVar += 1;
        console.log('Test variable inside 1st function: '+testVar);
    }
    function secondFunction() {
        testVar += 1;
        console.log('Test variable inside 2nd function: '+testVar);
    } 
    firstFunction();
    secondFunction();
    testVar += 1;
    console.log('Test variable outside: '+testVar);
Gawrion
  • 77
  • 1
  • 9
2

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global. References = https://www.freecodecamp.org/news/global-variables-in-javascript-explained/

Shrey Mittal
  • 61
  • 1
  • 2
2

All variables declared without "var" or "let" or anything else preceding it like "const" are global. So ....

function myFunction(){

     myVar = "value"; // myVar is a global variable and can be used anywhere inside <script> tags.

}
0

As an alternative to global vars, you may use the localstorage of browsers (if not using older versions). You can use upto 5MB of this storage. The code would be

var yourvariablevalue = 'this is a sample value';
localStorage.setItem("yourKeyvariablename", yourvariablevalue);

and this can be retrieved any time, even after you leave and open it at another time.

var yourvariablevalue = localStorage.getItem("yourKeyvariablename");

Hope this would help you !

Venugopal M
  • 2,280
  • 1
  • 20
  • 30
-1

If you are making a startup function, you can define global functions and variables this way:

function(globalScope)
{
    // Define something
    globalScope.something()
    {
        alert("It works");
    };
}(window)

Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konstantin Isaev
  • 642
  • 8
  • 14
-1

Here is sample code that might can be helpful.

var Human = function() {
    name = "Shohanur Rahaman";  // Global variable
    this.name = "Tuly"; // Constructor variable 
    var age = 21;
};

var shohan = new Human();

document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable 

Here I found a nice answer: How can one declare a global variable in JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shohanur Rahaman
  • 379
  • 4
  • 14
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Rohit Gupta Jul 24 '15 at 05:39
-1

To use the window object is not a good idea. As I see in comments,

'use strict';

function showMessage() {
    window.say_hello = 'hello!';
}

console.log(say_hello);

This will throw an error to use the say_hello variable we need to first call the showMessage function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mamé
  • 59
  • 5
-2

Here is another easy method to make the variable available in other functions without having to use global variables:

function makeObj() {
  // var trailimage = 'test';
  makeObj.trailimage = 'test';
}
function someOtherFunction() {
  document.write(makeObj.trailimage);
}

makeObj();
someOtherFunction();
am2124429
  • 425
  • 2
  • 6
  • 8