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
All scripts and functions in the same web page can access a variable with global scope. Each JavaScript function have their own scope.
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

javascript - How to declare a global variable in a .js file - Stack Overflow
I need a few global variables that I need in all .js files. For example, consider the following 4 files: global.js js1.js js2.js js3.js Is there a way that I can declare 3 global variables in glob... 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
How do JavaScript’s global variables really work?
TLDR; Everyone lied to you when they said let and const don't create global variables. They absolutely do .. it's just that they don't create window. global variables. More on reddit.com
🌐 r/javascript
47
137
July 7, 2019
Declaring a global variable in Jquery/Javascript
Nathan Marshall is having issues with: Hi Guys, I'm currently creating an application which allows me to set a username and password for a user. For them to later repeat the s... More on teamtreehouse.com
🌐 teamtreehouse.com
1
May 6, 2018
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Global_variable
Global variable - Glossary | MDN
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.
🌐
Playwright
playwright.dev › configuration
Configuration | Playwright
import { defineConfig } from '@playwright/test'; export default defineConfig({ // Folder for test artifacts such as screenshots, videos, traces, etc. outputDir: 'test-results', // path to the global setup files. globalSetup: require.resolve('./global-setup'), // path to the global teardown files.
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"
🌐
freeCodeCamp
freecodecamp.org › news › global-variables-in-javascript-explained
Global Variables in JavaScript Explained
January 26, 2020 - 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.
Find elsewhere
🌐
Hostman
hostman.com › tutorials › understanding global variables in javascript
Understanding Global Variables in JavaScript | Hostman
December 26, 2025 - Global variables in JavaScript are essential to programming as it offers accessibility throughout a script’s many sections. These are the variables that are defined outside of all functions and in the main body of the source code.
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › global-variable
Global Variables in JavaScript - Mastering JS
February 2, 2021 - In JavaScript, any variable defined outside any function or block is part of the global scope and is a global variable that any function can access.
🌐
Strapi
strapi.io › blog › global-variable-in-javascript
What Is a Global Variable in JavaScript?
November 25, 2025 - The variables share a name but not a memory location across the network boundary, so client-side mutations never affect server state. For values that rarely change, like API base URLs or feature flags read during initialization, this tradeoff often makes sense. For dynamic state that updates frequently, the false sense of synchronization makes globals a poor choice—one environment's changes never propagate to the other. JavaScript scope defines where variables are declared, accessible, and modifiable within your code.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › var
var - JavaScript | MDN
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 = ...
🌐
Quora
quora.com › How-can-I-make-a-global-variable-in-JavaScript-Do-I-have-to-declare-it-outside-of-any-function
How to make a global variable in JavaScript? Do I have to declare it outside of any function - Quora
Answer: you can set variables inside the global namespace of the program your running. but it isnt technically a GLOBAL VARIABLE in the sense that you can natively access it outside the function…
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_global_variables.htm
JavaScript - Global Variables
The global variables in JavaScript are the variables that are defined outside of the function or any particular block. They are accessible from anywhere in JavaScript code. All scripts and functions can access the global variables.
🌐
Reddit
reddit.com › r/javascript › how do javascript’s global variables really work?
r/javascript on Reddit: How do JavaScript’s global variables really work?
July 7, 2019 - Unlike var which defines a variable globally, suggesting only var defines global variables and let would not. And since the only concept of global that ever existed in JavaScript before this was that the global object (window) is global, then it's easy to see how this could be surprising.
🌐
Team Treehouse
teamtreehouse.com › community › declaring-a-global-variable-in-jqueryjavascript
Declaring a global variable in Jquery/Javascript (Example) | Treehouse Community
May 6, 2018 - The issue is when you assign values to the global variables. Variables are not dynamic, their value is static.
🌐
Substack
investinginai.substack.com › p › an-ai-analysis-of-zeta-global
An AI Analysis of Zeta Global - by Rob May
3 weeks ago - For modern organizations, marketing has always been one of the largest variable enterprise budget items.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-global-variables
JavaScript Global Variables - GeeksforGeeks
December 12, 2024 - Global variables in JavaScript are variables that can be accessed and modified from anywhere in the code, regardless of the scope where they were declared.
🌐
Contentful
contentful.com › blog › the-global-object-in-javascript
What is the global object in JavaScript? A practical guide for developers | Contentful
March 14, 2024 - We’ll explain how to use globalThis to access the global object later in this article — but first, it’s important to understand why it was necessary. ... scopes (also called contexts) determine where a variable or function that you have declared is accessible. Each scope has access to the functions and variables declared in its parent scopes. There is a precedence to how JavaScript resolves variables that appear inside scopes: if variables of the same name have been declared in multiple scopes, JavaScript uses the first one it finds, starting at the current scope, and working up toward the global scope.
🌐
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.