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>
Answer from T.J. Crowder on Stack Overflow
Top answer
1 of 16
947

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>
2 of 16
36

Just declare

var trialImage;

outside. Then

function makeObj(address) {
    trialImage = [address, 50, 50];
    ...
    ...
}
Top answer
1 of 6
230

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.

2 of 6
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.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 24605764 โ€บ global-variable-javascript
Global Variable JavaScript - Stack Overflow
I have a program where I use a global variable in an anonymous function. If I print my variable before the end of the function it is ok it has a value, but after the function it is empty. This is m...
Top answer
1 of 1
15

All JavaScript code executes in some environment, most commonly in a browser. The code that executes must execute in some "root" scope referred to as the global context or global scope (think of it as the main container). In your browser, this "root" scope is the window object (unique window object per tab, page, or iframe).

That is why when in the example a variable gets declared in the global scope var carName = "Volvo"; you can access this variable on the window object window.carName, because in the browser the 'window' object the global object.

When you execute JavaScript code using Node.js for example the global object is very aptly named global and in that environment if you declare var carName = "Volvo"; you can also access the variable using global.carName (this is only true on the Node.js REPL; var declarations in files do not attach to the global object).

To elaborate:

var myObject = { };
myObject.myVariable = 1;
console.log(myObject.myVariable); // Logs 1

myVariable is created on myObject, and this is done explicitly.

var myVariable = 1; // Behind the scenes this declaration is doing window.myVariable = 1;
console.log(window.myVariable); // Logs 1

myVariable is implicitly created on the window object which in the context of a browser is the global object.

For maybe a better explanation, I strongly recommend this book series You Don't Know JS Yet (book series) - 2nd Edition, specifically for this question You Don't Know JS Yet - Scope & Closures - 2nd Edition

Top answer
1 of 4
5

In your example, customer is a global variable. You should be able to do the following:

<button onclick="changeID(customer)">Add One to Customer ID</button>
2 of 4
3

Within the global scope (aka "window"), variables are global.

Check this out:

//this is global because it is in the global scope (the window)
var foo = 'stuff';
//because it is global (window) you can also access it like this:
console.log(window.foo); //'stuff'

Now you can access foo anywhere. It's worth noting that globals aren't best practice - so check out Object Oriented Programming (SOLID principles).

If you are within another scope (like a function) and don't use the var keyword to create a variable, the variable will be global:

function someFunction() {
  someVariable = 'stuff'; //this created a global variable! (or references an existing one)
  //you could also assign it to window:
  window.someVariable = 'stuff';
  //both are the same thing!
}

Inline js (onclick in your html) is not a good practice. Instead, you can follow the good practice and use javascript to register the click event:

//get reference to button
var myBtn = document.getElementById('myBtn');

//add click function
myBtn.addEventListener('click', function(event) {
  myFunction();
});

function myFunction() {
  console.log(foo); //'stuff' 
}

Here's a demo of all of this: http://jsbin.com/OmUBECaw/1/edit

Just note that you'll need to get the element references after they are loaded into the dom. It's best practice to include your scripts just before the end of the body rather than in the head, like this:

  <!-- scripts here! -->
  <script></script>
</body>

If you must keep the scripts in the head, then you'll need to put your javascript code in a function to run onload of the window:

window.addEventListener('load', function() {
  //code here!
});
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_scope.asp
JavaScript Scope
Any function, including the window object, can overwrite your global variables and functions. The lifetime of a JavaScript variable starts when it is declared.
Top answer
1 of 2
4

Javascript is single-threaded, if you have a loop like:

while(!downloadFinished) {

}

that loop will keep running forever and no other function will run (your .on('complete' callback can't execute until the while loop finishes, because of the single-threaded nature of Javascript, so it won't ever finish since you don't set downloadFinished = true inside that loop or use a break statement).

To work around this, you can do all your other stuff in a callback which you don't call until the download completed:

var downloadPage = function(url, file, callback) {
  rest.get(url).on('complete', function(result) {
    if (result instanceof Error) {
      console.log('Error:', result.message);
    } else {

      /* Don't use writeFileSync, unless you want to block your server,
        from handling any requests at all until the disk IO completes

        fs.writeFileSync(file, result, 'utf8');
        callback();
      */
      fs.writeFile(file, result, 'utf8', callback);
    }   
  }); 
};

if(require.main == module) {
    downloadPage('http://google.com', 'new.html', function after_download(){
        // do other stuff make sure download is finished to 'new.html'
    });
}
2 of 2
1

When you call that while(!downloadFinished) it is set to false so you are basically doing while(true).

Option 1

You can use a callback instead of a while loop.

var successCallback = function() {
 //do stuff here.
};

var downloadPage = function(url, file, callback) {
  rest.get(url).on('complete', function(result) {
  if (result instanceof Error) {
    console.log('Error:', result.message);
  } else {
    fs.writeFile(file, result, 'utf8', callback);
   }   
  }); 
};

if(require.main == module) {
    downloadPage('http://google.com', 'new.html', successCallback);
}

Option 2

Check out Promises they will really help you here. You could use Bluebird a nice Promise library you can just add to your package dependencies.

Find elsewhere
Top answer
1 of 5
100

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

2 of 5
93

The recommended approach is:

window.greeting = "Hello World!"

You can then access it within any function:

function foo() {

   alert(greeting); // Hello World!
   alert(window["greeting"]); // Hello World!
   alert(window.greeting); // Hello World! (recommended)

}

This approach is preferred for two reasons.

  1. The intent is explicit. The use of the var keyword can easily lead to declaring global vars that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var or the prefix window.

  2. You standardize this syntax for reading the variables this way as well which means that a locally scoped var doesn't clobber the global var or vice versa. For example what happens here is ambiguous:

 

 greeting = "Aloha";

 function foo() {
     greeting = "Hello"; // overrides global!
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // does it alert "Hello" or "Howdy" ?

However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):

 function foo() {
     window.greeting = "Hello";
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // alerts "Howdy"
Top answer
1 of 10
149

You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.

<script type='text/javascript' > 
  var myFunctionTag = false; 
</script>
<script type='text/javascript' src='js/helpers.js'></script>     
... 
<script type='text/javascript' > 
  // rest of your code, which may depend on helpers.js
</script>
2 of 10
19

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?

All the results were as expected.

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.

My example files follow:

EXTERNAL JS:

var global = 0;

function f1()
{
    alert('fired: f1');
    global = 1;
    alert('global changed to 1');
}

function f2()
{
    alert('fired f2');
    alert('value of global: '+global);
}

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Top answer
1 of 3
8

The problem with globals is not memory, and it's not performance.

The problems with globals is entirely different. The problems are that they introduce global state and that scripts are not bound to a namespace.

Let's go through these problems one by one.

Having global state

This is the biggest issue here. Coding necessitates that the dependencies of a module be explicit and that communication between pieces of code is very clear.

When you have global variables which part of the code uses the variable is not nearly as clear and you can't be sure what part of the code needs it and what does not.

Let's say I have a Zoo project and I have a Bathe service that cleans an animal. Instead of passing Bathe around to each animal that needs it I have it on a global namespace and I just call Bathe(myAnimal).

Now I want to restructure my zoo and I want to know which animals need bathing because I want to optimize that. I have no way of knowing that other than going through my whole code. In order to see if my Giraffe needs bathing I have to read the entire code of the Giraffe class. If instead I passed Bathe to the constructor of Giraffe instead of using it or creating it inside giraffe (a concept called dependency injection) I can see that a Giraffe needs bathing just by reading the signature.

Now this can get way worse, what if I have state? If I'm actually changing a global variable in multiple places it becomes extremely hard to track. In a more than a few lines code base this means that you have state changing all around and no clear indication of who is changing it.

This is the main reason you should avoid globals altogether .

Scripts are not bound to a namespace

If I have two scripts on a page and my first script declares a A variable on the global namespace, the second script can access that variable. This is useful because scripts can interact this way but it's very harmful because it means that scripts can override each other's code, and communicate in an unclear way.

This of course is completely mitigated if you use a module loader like browserify or RequireJS which means your whole script only exposes two globals - require and define and then script loading is done through the loader.

This way the way independent pieces of code interact is well defined. That doesn't prevent you from creating variables on the global object, but it helps mitigating the need to do so in a uniform manner.

A note on security

Of course, anything on the client side is compromised, you can't do security or anything like that in client side JavaScript on an insecure browser (that is, you didn't prevent anything external on) because the client can just run arbitrary code on your code and read it.

2 of 3
5

There are three big problems with global variables:

  1. name collisions
  2. code complexity
  3. garbage collection

Name collision

The problem with having variables in global scope is that you have less control over what else is in that scope. Your code uses a ga_ variable globally and works fine, but when you add a Google Analytics snippet that uses the same variable things unexpectedly fail and it can be quite hard to see why your shopping cart fails 2 out of 3 page loads.

If you can wrap your code in an IIFE to prevent having any variables in global scope, you should do that. Obviously there are cases where you actually want to have your code accessible globally (ex: jQuery library). In those cases, it is best practice to keep all your stuff in a single namespace (jQuery) with a relevant name.

Code complexity

It is usually a good idea to partition your code so that individual pieces have minimal interactions with each other. The more pieces interact the harder it is to make changes and to track down where bugs come from. Obviously a global variable can be accessed anywhere so when you have a problem with some code that accesses a global variable, you have to inspect every usage of that variable which can be quite a big pain. The thing to do to avoid these pains is to keep variables as local as they can be and encapsulate pieces of code so they can't interact with each other except through specific interfaces.

Memory leaks

In JavaScript you have little control over the garbage collection process. All that is guaranteed is that if you can access a variable it will not be garbage collected. This means that if you want something to be garbage collected, then you must make sure you can't access it anymore. While a global i variable which keeps a number won't be a big deal, as @Boluc Papuaccoglu mentioned when your global variable keeps more and more properties over time (an array of XHR requests for example, or array of created DOM objects), the memory consumption turn into a big deal.

All of these situations are worst case scenarios and you probably won't have issues with a small application. These recomendations have most value when you're starting to learn programming because they develop good habits and when you're working on complex applications when they save you time and money wasted on debug or difficult to do improvements.

Top answer
1 of 3
3

Functions are objects. They can have properties like any other objects:

function a(){
    if (a.executed) return;
    a.executed = true;

    //do stuff
}

As @Ian mentioned in his comment you can easy make the function reusable. It can be advantage as well as a downside of this approach.

And as @Dave said it can be achieved with closure:

var a = (function (){
    var executed = false;

    return function (){
        if (executed) return;
        executed = true;

        //do stuff
    }
})(); 
2 of 3
3

No, there's no good reason to use global variables for this. It's easy enough to just wrap all your code in a function to avoid polluting the global namespace:

(function() {
    //all your code here
})();

But I think a better solution would be to remove the event handler upon clicking the button instead. Here's an example:

HTML:

<button id="click_me">Click me</button>

JavaScript:

function click_function() {
    alert('You clicked the button with ID ' + this.id);
}

function click_listener() {
    click_function.call(this);
    this.removeEventListener('click', click_listener);
}

document.getElementById('click_me').addEventListener('click', click_listener);


Alternatively, some JS libraries make it easy to assign a handler that will only fire once. In fact, I highly recommend this: you won't have to type nearly as much code. For example, when using jQuery you can just write:

$('#click_me').one('click', function() {
    alert('You clicked the button with ID ' + this.id);
});

This does the same thing as the above code, except it's compatible with more browsers, including older versions of IE.