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.
๐ŸŒ
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
๐ŸŒ
W3docs
w3docs.com โ€บ javascript
How to Define Global Variable in a JavaScript Function
Alternatively, assign the property to a window because, in JavaScript, you can define global variables inside a function using the window object.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-change-the-value-of-a-global-variable-inside-of-a-function-using-javascript
How to change the value of a global variable inside of a function using JavaScript ? | GeeksforGeeks
April 13, 2023 - There are two ways to declare a variable globally: Declare a variable outside the functions. Assign a value to a variable inside a function without declaring it using the "var" keyword.
๐ŸŒ
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
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 4f85a3e0f37bc30003039312
Can you change a global variable's value from within a function? | Codecademy
For example: var global = "Global Variable"; //Define global variable outside of function function setGlobal(){ global = "Hello World!"; }; setGlobal(); console.log(global); //This will print out "Hello World"
Find elsewhere
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ how-to-create-a-global-variable-inside-a-function
How to create a global variable inside a function (Example) | Treehouse Community
April 13, 2014 - function thingToDo() { var infoINeed = "whatever"; return { thing1: infoINeed, thing2: "something else" }; } // assign the executed function to a variable for easy use var obj = thingToDo(); // Then, later, you can get that information, this ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ global-variables-in-javascript-explained
Global Variables in JavaScript Explained
January 26, 2020 - var x = 5; // global function someThing(y) { var z = x + y; console.log(z); } function someThing(y) { x = 5; // still global! var z = x + y; console.log(z); } function someThing(y) { var x = 5; // local var z = x + y; console.log(z); } A global ...
๐ŸŒ
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 ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ What-is-the-correct-way-to-define-global-variables-in-JavaScript
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 ...
๐ŸŒ
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.
๐ŸŒ
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 - 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).
๐ŸŒ
Snook
snook.ca โ€บ archives โ€บ javascript โ€บ global_variable
Global Variables in JavaScript - Snook.ca
If you want to declare a variable in the global scope from within any function, just omit the var keyword: (function () { x = 5; })(); alert((x * 10)); // alerts "50" This is really bad practice though, so refrain from doing so if at all possible.
Top answer
1 of 3
4

Javascript is pass-by-value. (Objects, arrays, and other non-primitives are passed by value-of-reference.) That means that the value of the variable (or reference) is passed to the function, but the function parameter does not become an alias for the actual argument. Thus, you cannot change a variable outside a function without referencing it (as you do in your last example).

See this answer in another thread for more information.

2 of 3
1

Inside of functions are "variable environments". When the function setup is declared, and the parameter variable set, it creates a local variable in setup's variable environment for variable (the parameter).

So that is why this assignment

function setup(variable) {
 variable = 7;
}

Will never change the value sent to variable.

Variables in JavaScript are values. As the variable is passed around, the only thing passed is the value of the variable. However, the value of the variable is assigned to the parameter (again poorly named in this example) variable. When the value of the parameter is assigned to 7, that only changes the local variable, and not the value of the passed variable.

//the value of things is 5
var things = 5;

//the passed value 5 is assigned to variable
function setup(variable) {
  //the value of variable is changed to 7 (and nothing is done with 5)
  variable = 7;
}

//the value of things is sent to setup
setup(things);

Hopefully this will be a little more enlightening. Consider a situation where setup was actually modifying the value of variable. A good example is when the value has state, such as an array or an object.

//the value of things this time is an object
var things = {};

//the passed value of object is assigned to variable
function setup(variable){
 //the value of variable (the object) has a property added named msg with a value of "hello world"
 variable.msg = "hello world";
}

//the value of things (an object) is sent to setup
setup(things);
alert(things.msg);//hello world
๐ŸŒ
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.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ var
var - JavaScript | MDN
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.