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
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_scope.asp
JavaScript Scope
JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Syllabus JS Study Plan JS Interview Prep JS Bootcamp JS Certificate JS Reference ... Scope determines the accessibility (visibility) of variables. ... Variables declared Globally (outside any block or function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript ...
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];
    ...
    ...
}
Discussions

How to declare a global variable in JavaScript - Stack Overflow
See How to get the global object in JavaScript? 2016-11-30T15:50:21.943Z+00:00 ... The global object in node.js is the same as the window object in browsers 2022-03-17T23:55:33.69Z+00:00 ... 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... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Global Variable in Javascript
You can access a value from any JavaScript code running in a window by adding it as property to the "global context", usually window in the browser, though you can also use globalThis which will work anywhere. window.myName = 'Sue'; globalThis.myAge = 37; // elsewhere in another file... console.log(globalThis.myName); // Sue console.log(window.myAge); // 37 It should be noted that this sort of setup works fine for a down-and-dirty weekend project, but scales poorly as your project grows. For one, a bunch of important stuff is already on the global context, and you may accidentally erase or alter it. You can mitigate this issue somewhat by using a single object for all of your global variables. window.MyGlobalVariables = {}; window.MyGlobalVariables.myName = 'Sue'; Still, even with this more cautious approach, there are few good reasons to use global variables. For almost any use case, you will want to use JavaScript modules with import and export . // In names.js... export const myName = 'Sue'; // In some other file... import { myName } from './names.js'; More on reddit.com
๐ŸŒ r/learnjavascript
6
1
August 5, 2024
JavaScript Global Variable
Abe Layee is having issues with: I am current working on my JavaScript skill. However, I came across some bug or whatever it may be called. When I had a global varialbe, the set... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
6
August 26, 2015
Is using Global Variables always bad?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
6
6
November 28, 2023
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-declare-global-variables-in-javascript
How to declare Global Variables in JavaScript ? - GeeksforGeeks
July 23, 2025 - Variables declared in this way are accessible from anywhere within the script. ... // Declare global variables outside of any function or block scope var globalVar1 = "Hello"; let globalVar2 = "World"; const globalVar3 = "!"; Example ...
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.

๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Glossary โ€บ Global_variable
Global variable - Glossary - MDN Web Docs
A global variable is a variable that is declared in the global scope in other words, a variable that is visible from all other scopes. In JavaScript it is a property of the global object.
๐ŸŒ
Medium
medium.com โ€บ @jambiebs โ€บ javascript-global-variable-fec37d62f44
JavaScript Global Variable. javascript global variable example | by Md Jamal | Medium
June 29, 2023 - In the example above, `myGlobalVariable` is declared with `var` outside of any function, making it a global variable. It can be accessed and used from both the `myFunction` function and the top-level scope. However, itโ€™s worth noting that in modern JavaScript, the `let` and `const` keywords are preferred over `var` due to their block scope.
Find elsewhere
๐ŸŒ
web.dev
web.dev โ€บ articles โ€บ global and local variable scope
Global and local variable scope | Articles | web.dev
April 14, 2022 - When a variable is accessed within its scope, JavaScript returns its assigned value or otherwise produces an error. ... Use the var, const, or let keywords to declare local or global-scope variables. Use the const or let keywords to declare block-scope variables. When you declare a var variable in a function, the declaration makes the variable available to the nearest enclosing function. You can't use the var keyword to declare variables with block scope. This example demonstrates global scope because the greeting variable is declared outside of any function or block, which makes its value available to all code in the current document:
๐ŸŒ
Medium
habtesoft.medium.com โ€บ global-variables-in-javascript-understanding-and-best-practices-dbd7dd6f1067
Global Variables in JavaScript: Understanding and Best Practices | by habtesoft | Medium
November 13, 2024 - let globalVar = 'I am a global variable'; function showGlobal() { console.log(globalVar); // Accessible inside functions } showGlobal(); // Output: "I am a global variable" console.log(globalVar); // Output: "I am a global variable" In the example ...
๐ŸŒ
Flexiple
flexiple.com โ€บ javascript โ€บ global-variables
Global Variables In JavaScript - Flexiple
April 30, 2024 - In the example above, globalVar is declared as a global variable and is accessible both inside and outside of the testFunction. JavaScript developers are advised to limit the use of global variables to avoid potential issues with code maintainability and readability.
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ variable-scope
JavaScript Variable Scope (with Examples)
In the above program, variable a is a global variable. Had the variable been declared using let a = "hello", the program would have thrown an error. Note: JavaScript has a strict mode in which a variable cannot be used without declaring it. JavaScript ES6 introduced block-level scoping with the let and const keywords. Block-level variables are accessible only within the block {} they are defined in, which can be smaller than a function's scope. For example,
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ javascript
Javascript Global Variables-How to create and access them in JS
September 12, 2022 - OUTPUT > Inside function : Jack ... (javascript) Global variables that we declared are kept inside a global object. In the browser, our global variables are automatically assigned as a property of the window object. We can access the username variable using username or window.username as in the following example...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ global-variables-in-javascript-explained
Global Variables in JavaScript Explained
January 26, 2020 - The scope of JavaScript variables are either global or local. Global variables are declared OUTSIDE the function and its value is accessible/changeable throughout the program. You should ALWAYS use var to declare your variables (to make locally) else it will install GLOBALLY ยท Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables. Example...
๐ŸŒ
BitDegree
bitdegree.org โ€บ learn โ€บ best-code-editor โ€บ javascript-global-variable-example-4
JavaScript Global Variable: Example of HTML Usage
Global variables belong to the window object in HTML and will be deleted when you close it. See this JavaScript global variable example to grasp the idea.
๐ŸŒ
Strapi
strapi.io โ€บ blog โ€บ global-variable-in-javascript
What Is a Global Variable in JavaScript?
November 25, 2025 - This pattern follows guidance from Treehouse's tutorial on minimizing globals and aligns with JavaScript best practices recommended by the development community. Only MyApp and MyApp.auth appear in the global scope; everything else stays secured inside the closure. Even careful architecture can't prevent accidental variable creation.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ var
var - JavaScript - MDN Web Docs - Mozilla
The var statement declares function-scoped or globally-scoped variables, optionally initializing each to a value. var x = 1; if (x === 1) { var x = 2; console.log(x); // Expected output: 2 } console.log(x); // Expected output: 2 ... var name1; var name1 = value1; var name1 = value1, name2 = ...
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ global variable in javascript
Global Variable in JavaScript - Tabnine
July 25, 2024 - Block statements do not create their own scope when included outside of a function, thus variables declared inside blocks are global (using the const or let keywords changes this). The following examples explore working with global variables and scopes.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript โ€บ javascript_global_variables.htm
JavaScript - Global Variables
Even if we have defined the variable in the function, it becomes global as we haven't used any keyword to define the function. The output shows that variable 'a' can be accessible inside or outside the function. <html> <head> <title> JavaScript - Global variables </title> </head> <body> <p id = "demo"> </p> <script> const output = document.getElementById("demo"); function test() { a = 90; output.innerHTML += "a -> Inside the function = " + a + "<br>"; } test(); output.innerHTML += "a -> Outside the function = " + a + "<br>"; </script> </body> </html>
๐ŸŒ
Mozilla
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Guide โ€บ Grammar_and_types
Grammar and types - JavaScript - MDN - Mozilla
With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables, depending on the execution context.