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 OverflowAs 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>
Just declare
var trialImage;
outside. Then
function makeObj(address) {
trialImage = [address, 50, 50];
...
...
}
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.
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.
Videos
You can assign to the window object, i.e. window.myGlobal = 3;. window is the default context for variable binding. That's why you can reference document instead of needing to do a window.document.
But yeah as David says, you should avoid using globals. And if you are going to use globals, you should place them and other top-level declarations in a "namespace" object to avoid potential naming collisions with other libraries, like this:
myNamespace = { myGlobal: 3 };
// Then to access...
myNamespace.myGlobal = 6;
Don't use the var keyword
(That said, globals are usually the wrong solution to any given problem in JS)
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>
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!
});
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'
});
}
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.
A good technique for this is a self-executing closure:
// bob is a global variable, which you want to avoid
var bob = 1;
// By wrapping this function declaration in parentheses, then
// appending (), it gets invoked immediately. But everything
// inside it is scoped to the anonymous function!
(function () {
// sue can only be seen inside this function
var sue = 1;
// But if you want to, you can still create global variables.
// This creates a global variable called joe:
window.joe = 1;
})();
Applying this technique to your code, you could write this to have no global variables:
(function() {
var size_li = $("#myList li").size();
var x = 3;
$('#myList li:lt(' + x + ')').show();
$('.loadmore').on('click', function() {
x = (x + 2 <= size_li) ? x + 2 : size_li;
$('#myList li:lt(' + x + ')').show();
});
})();
The way I know is in es6, which has 'let' could define a variable inside block
eg:
var b = 5
{
let a = 10
}
a//undefine
b// is 5
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.
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.
The intent is explicit. The use of the
varkeyword can easily lead to declaring globalvarsthat 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 keywordvaror the prefixwindow.You standardize this syntax for reading the variables this way as well which means that a locally scoped
vardoesn't clobber the globalvaror 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"
They clutter up the global namespace and are slower to look up than local variables.
First of all, having many global variables is always a bad thing because it's easy to forget you declared a variable somewhere and accidentally re-declare it somewhere else. If your first variable was local then you don't have a problem. If it was global, then it just got overwritten. This gets even worse when you get into implied globals (e.g. when you say someVar = someValue without declaring someVar with the var keyword).
Secondly, global variables take longer for Javascript to "find" than local variables. The difference in speed isn't huge, but it does exist.
For further reading and a more in-depth explanation of why globals are considered bad practice, you may want to check out this page.
Global variables can significantly increase coupling, significantly reduces the scalability and testability of your code. Once you start using globals, you now have to know where and how the variable is modified (i.e. breaking encapsulation). Most of the literature and conventions out there will argue that performance is the least of your concerns when using globals.
This is a fantastic article outlining why global variables cause headaches.
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>
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
- One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
- Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
- One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
- It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
- They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
- 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>
Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.
You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.
That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
alert("Value of 'a' outside the function " + a); //outputs 20
You have to call myFunction() first, e.g.:
myFunction();
alert(x);
It should be called myFunction, myFunction(), first before the alert. This is why you get 0. When this script is loaded the value of x is 0. Hence the alert will alert 0. Then each time a user clicks on the button you have referred to, the value of x would be incremented by 1. That being said, I think that you need something like this:
function myFunction() {
// when the button will be clicked the value of x
// would be incremented by one.
x += 1
// the new value would be alerted.
alert(x);
}
Another way it would be this:
myFunction();
alert(x);
However, this doesn't make sense, since you need to increment the value of x each time the button is clicked and you don't need to force the execution of myFunction.
I'd bet on it being caused by some slight confusion...
Being that putting var in front of a variable puts that variable into the local scope only in Javascript, and a variable delcaration without it (a = 16) is global.
function test() {
a = 16;
var b = 16;
}
test();
alert(a); # alerts 16
alert(b); # throws error, b is undefined
This is just a simple concept of global and local variable.. when You run the method the variable which is global has got its value and the variable which is local has also got the value but its lifecycle expires on going out of function thus it throws error to be undefined
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.
There are three big problems with global variables:
- name collisions
- code complexity
- 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.
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
}
})();
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.
You have nothing to worry about.
The performance impact of a global variable is minute.
Global variables are discouraged because they can make code harder to maintain.
In your case, they won't.
The reason global variable use should be kept to a minimum is because the global namespace gets polluted when there's a lot of them, and there's a good chance of a clash if your program needs to use some 3rd party libraries which also create their own globals.
Creating a single object to hold all of your global state is a good idea since it limits the number of identifiers you need to reserve at the global level.
To solve performance problems, you can then create a local reference to that object in any scope where you need to access it multiple times:
So instead of
if (globalState.isIe) { alert(globalState.ieMessage); }
you can do
var state = globalState;
if (state.isIe) { alert(state.ieMessage); }
You don't need to do this if you only access the state object once. In any case, even if you never do this, the performance penalties will be negligible.