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];
    ...
    ...
}
🌐
W3Schools
w3schools.com › js › js_scope.asp
JavaScript Scope
Arguments (parameters) work as local variables inside functions · Before ES6, JavaScript variables could only have Global Scope or Function Scope.
Discussions

javascript - How do I change the value of a global variable inside of a function - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am using JavaScript and I create a global variable. I define it outside of a function and I want to change the global variable value from inside a function and use it from another function, ... 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
Changing a global variable's value with a function with the variable passed as an argument
I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return num; } · I get 55 back when I input a as an argument, but globally, a is still ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 30, 2020
A bit stupid question regarding accessing global variable from inside a loop in function
The assignment operation, total *= number, makes total inside the function local to the function and independent of the variable with the same name outside the function. You could get over this using global but generally its usage should be avoiding in all but very special use cases. Pass the object instead using the variable name: def product(list_, total): for number in list_: total *= number return total total = 1 total = product([4, 5, 6, 7], total) print(total) PS. Do not use predefined Python names/types/classes/keywords as variables, it will cause you problems. Hence, my adding _ to list above. More on reddit.com
🌐 r/learnpython
11
1
October 15, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-declare-global-variables-in-javascript
How to declare Global Variables in JavaScript ? - GeeksforGeeks
July 23, 2025 - // Declare global variables outside of any function or block scope var globalVar1 = "Hello"; let globalVar2 = "World"; const globalVar3 = "!"; Example 1: Declaring Global Variables in JavaScript
🌐
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.
🌐
Javatpoint
javatpoint.com › javascript-global-variable
JavaScript global variable - javatpoint
JavaScript global variable tutorial for beginners and professionals with example, declaring javascript global variable within function, internals of global variable in javascript, event, validation, object loop, array, document, tutorial
Find elsewhere
🌐
W3docs
w3docs.com › javascript
How to Define Global Variable in a JavaScript Function
Global variables have a global JavaScript scope. All functions can access it throughout the whole web page. To share a value between two or more script sections on your web page, you can define a global variable and assign a value to it in one ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › var
var - JavaScript - MDN Web Docs - Mozilla
Be careful of the var x = y = 1 syntax — y is not actually declared as a variable, so y = 1 is an unqualified identifier assignment, which creates a global variable in non-strict mode. ... var x = 0; function f() { var x = y = 1; // Declares x locally; declares y globally.
🌐
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.
🌐
Scaler
scaler.com › home › topics › what is global variable javascript?
What is Global Variable JavaScript? - Scaler Topics
May 7, 2024 - As result, when add function get ... a global variable in javascript we have to declare a var, const or let variable outside of any block or function, inside the global scope....
🌐
Tabnine
tabnine.com › home › global variable in javascript
Global Variable in JavaScript - Tabnine
July 25, 2024 - A Global variable is a variable that is declared in the global scope, making it a property of the global object. Global variables are accessible from all other (local) scopes. The global scope is a scope that contains every variable declared ...
🌐
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 above, globalVar is declared in the global scope, meaning it can be accessed anywhere in the program. ... Passionate JavaScript developer with a focus on backend technologies.
🌐
Flexiple
flexiple.com › javascript › global-variables
Global Variables In JavaScript - Flexiple
April 30, 2024 - Global Variables in JavaScript refers to variables that are accessible from any part of a JavaScript program. Developers declare global variables outside any function or simply omit the use of 'var', 'let', or 'const' inside a function.
🌐
freeCodeCamp
forum.freecodecamp.org › t › changing-a-global-variables-value-with-a-function-with-the-variable-passed-as-an-argument › 381692
Changing a global variable's value with a function with the variable passed as an argument - The freeCodeCamp Forum
April 30, 2020 - I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return num; } · I get 55 back when I input a as an argument, but globally, a is still ...
🌐
Hostman
hostman.com › tutorials › understanding global variables in javascript
Understanding Global Variables in JavaScript | Hostman
December 26, 2025 - The var keyword is the oldest way to declare a variable. Variables declared outside of a function can be accessed globally, while variables declared inside a specific function can be accessed within that function.
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
GeeksforGeeks
geeksforgeeks.org › global-and-local-variables-in-javascript
Global and Local variables in JavaScript | GeeksforGeeks
Automatic Global Variables: If a variable is declared inside a function without var, let, or const, it automatically becomes a global variable (a common source of bugs). Local variables are defined within functions in JavaScript.
Published   August 20, 2024
🌐
Medium
medium.com › @krishnaregmi › accessing-global-variable-in-javascript-ea457b4ab70a
Why can’t I access global variables inside my function in Javascript ? | by Krishna Regmi | Medium
April 22, 2019 - Javascript will tell you that globalVariable is not defined ReferenceError:globalVariable is not defined · This is because regardless of where you define your variable, it will hoist the variable to the top of their enclosing scope. Which means, if a variable is defined in a scope, javascript moves it all the way at the top of the scope. This is the same reason you can call a function in javascript on line 1 even though the function doesn’t get defined until line 2.
🌐
Codedamn
codedamn.com › news › javascript
Javascript Global Variables-How to create and access them in JS
September 12, 2022 - OUTPUT > Inside function : Jack > Outside function : JackCode language: JavaScript (javascript) Global variables that we declared are kept inside a global object. In the browser, our global variables are automatically assigned as a property ...
🌐
Quora
quora.com › In-JavaScript-is-there-a-way-from-within-a-function-to-declare-a-variable-to-the-global-scope
In JavaScript, is there a way from within a function to declare a variable to the global scope? - Quora
Answer (1 of 3): If you must declare a global variable, then do it OUTSIDE the function for goodness’ sake! Under normal circumstances, global variables should only be used for data that never changes once it’s initialized. Even then it's not a particularly great idea.