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.

Answer from Spudley on Stack Overflow
🌐
Codecademy
codecademy.com › forum_questions › 4f85a3e0f37bc30003039312
Can you change a global variable's value from within a function? | Codecademy
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" ...
Discussions

javascript - jquery change global variable inside function - Stack Overflow
Does in possible to change global variable inside function without return ? I need after call function change have output "after" ... It is possible, but why would you use globals to begin with? Why can't the function take one argument? ... You may want to check this question, because that's seems like a pretty common mistake. ... Short answer is yes. Long answer is you should read this, and this, to get to know all you need about scopes in JavaScript... More on stackoverflow.com
🌐 stackoverflow.com
How do I update a global variable from inside of an arrow function?
This is an asynchronous issue. You are passing a callback function to getCurrentPosition because the function is not going to give you a result back until later. Your getLocation function by contrast is synchronous. It returns a result right now. That is why "but location is null here" logs before "loc inside function". Everything you are doing with the variables and returns is fine, but the order is wrong. So how do you fix it? Well, once something is asynchronous, everything downstream must also be asynchronous. This can be a pain, but it makes sense if you think about it. Anything synchronous happens now. There is no way for code that is running now to time travel and get values that do not resolve until later. So your function must become asynchronous. It cannot simply return the value. The simplest way to do this is to just use a callback function just like getCurrentPosition does. function getLocation(onDone) { let loc = null; if (navigator) { navigator.geolocation.getCurrentPosition( ({ coords }) => { loc = { "latitude": coords.latitude, "longitude": coords.longitude }; onDone(loc); } ); } else { onDone(loc); } } We could perhaps simplify ths code further, but this is the minimum change to get your function working. Notice we are no longer returning anything. Instead, you pass in an onDone function, and that function will eventually be called with the location. getLocation((loc) => { console.log(loc); }); Now, most modern JS does not use callbacks for asynchronous code like this, instead wrapping callbacks in Promises . This will require a little more work upfront, but will ultimately allow you to use the .then or async/await syntax, which is a little easier. function getLocation() { return new Promise((resolve) => { if (navigator) { navigator.geolocation.getCurrentPosition( ({ coords }) => { resolve(coords); } ); } else { resolve(null); } }) } I've simplified things a bit here, but the basic structure is the same. We're returning a Promise object, which is basically an IOU. Eventually, it will resolve to some value. Notice that the Promise's resolve function has basically replaced our onDone from before. Under the hood, Promises are built on callbacks. But a Promise let's us do neat tricks like this: async function logLoc() { let loc = await getLocation(); console.log(loc); } logLoc(); This async function will pause its execution until the Promise we returned resolves. The resulting code looks almost synchronous. More on reddit.com
🌐 r/learnjavascript
6
4
June 5, 2022
Not Clear How a Function Can Overwrite a Global Variable
Using the keyword var within the function creates a new variable with the same name as the global variable that was defined above the function. If you omit the keyword 'var' in the function definition, you'll change the global variable. Call tripOut() with and without the var keyword to see what ... More on teamtreehouse.com
🌐 teamtreehouse.com
3
December 1, 2016
update global variable from a function in the javascript - Stack Overflow
Here is the situation: I have one function which has local variable. I would like to assign that value to global variable and us it's value in another function. Here is the code: global_var = "... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-change-the-value-of-a-global-variable-inside-of-a-function-using-javascript
Change the value of a global variable inside of a function using JavaScript - GeeksforGeeks
November 3, 2025 - <body> <h1 style="color:green"> GeeksForGeeks </h1> <b>Enter first number :- </b> <input type="number" id="fNum"> <br><br> <b>Enter second number :- </b> <input type="number" id="sNum"> <br><br> <button onclick="add()">Add</button> <button onclick="subtract()">Subtract</button> <p id="result" style="color:green; font-weight:bold;"> </p> <script> // Declare global variables var globalFirstNum1 = 9; var globalSecondNum1 = 8; function add() { // Access and change globalFirstNum1 and globalSecondNum1 globalFirstNum1 = Number(document.getElementById("fNum").value); globalSecondNum1 = Number(documen
🌐
TutorialsPoint
tutorialspoint.com › 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?
Following syntax will help you to understand how to you can directly access and change the value of the global variable ? var global_variable_name = initial_value; function() { global_variable_name = new_value; } Let us understand the practical implementation of this method with help of JavaScript ...
🌐
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.
🌐
SheCodes
shecodes.io › athena › 18058-how-to-use-a-function-to-change-the-value-of-a-global-variable-in-javascript
[JavaScript] - How to use a function to change the value of a global variable in JavaScript
Learn how to update the value of a global variable using a function in JavaScript, with an example code snippet. Asked almost 3 years ago in JavaScript by Anne-Marie · can I use a function to change the value of a global variable in javascript?
Find elsewhere
🌐
W3Schools
w3schools.com › js › js_scope.asp
JavaScript Scope
Variables declared Globally (outside any block or function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program.
🌐
YouTube
youtube.com › telusko
#25 Local-Global Variable | Default Value in JavaScript - YouTube
Instagram : https://www.instagram.com/navinreddyofficial/Linkedin : https://in.linkedin.com/in/navinreddy20Discord : https://discord.gg/aXPF5hV7More Learning...
Published   June 10, 2021
Views   66K
🌐
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. Always eager to connect and learn.
🌐
Quora
quora.com › Can-you-declare-a-global-variable-in-function-JavaScript
Can you declare a global variable in function JavaScript? - Quora
Answer: You technically can. But you shouldn’t. If you need to variable to be global, it means it can be use anywhere at any time. If you declare it inside a function, it won’t be there until the function is called. There is really no point to that. It sounds like you are describing a logic ...
🌐
Javatpoint
javatpoint.com › javascript-global-variable
JavaScript global variable - javatpoint
In JavaScript, a switch case is a conditional statement that is used so it can provide a way to execute the statements based on their conditions or different conditions. A switch case statement is used to perform different actions based on... ... JavaScript Variable JavaScript variable JavaScript Local variable JavaScript Global variable A JavaScript variable is simply a name of storage location. The actual value of a variable can be changed at any time.
🌐
Reddit
reddit.com › r/learnjavascript › how do i update a global variable from inside of an arrow function?
r/learnjavascript on Reddit: How do I update a global variable from inside of an arrow function?
June 5, 2022 -

I am trying to write a module which will get the location from the browser (navigator.geolocation) and returns the result.

But the "location" I get like this only lives inside the function it calls. How do I return the location?

function getLocation() {
  let loc = null;
  if (navigator) {
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        loc = {
          "latitude": coords.latitude,
          "longitude": coords.longitude
        };
        console.log("loc inside function as desired:", loc);

      }
    );
  }

  console.log("but loc is 'null' here:", loc);

  return loc;
}

export default getLocation;
Top answer
1 of 3
8
This is an asynchronous issue. You are passing a callback function to getCurrentPosition because the function is not going to give you a result back until later. Your getLocation function by contrast is synchronous. It returns a result right now. That is why "but location is null here" logs before "loc inside function". Everything you are doing with the variables and returns is fine, but the order is wrong. So how do you fix it? Well, once something is asynchronous, everything downstream must also be asynchronous. This can be a pain, but it makes sense if you think about it. Anything synchronous happens now. There is no way for code that is running now to time travel and get values that do not resolve until later. So your function must become asynchronous. It cannot simply return the value. The simplest way to do this is to just use a callback function just like getCurrentPosition does. function getLocation(onDone) { let loc = null; if (navigator) { navigator.geolocation.getCurrentPosition( ({ coords }) => { loc = { "latitude": coords.latitude, "longitude": coords.longitude }; onDone(loc); } ); } else { onDone(loc); } } We could perhaps simplify ths code further, but this is the minimum change to get your function working. Notice we are no longer returning anything. Instead, you pass in an onDone function, and that function will eventually be called with the location. getLocation((loc) => { console.log(loc); }); Now, most modern JS does not use callbacks for asynchronous code like this, instead wrapping callbacks in Promises . This will require a little more work upfront, but will ultimately allow you to use the .then or async/await syntax, which is a little easier. function getLocation() { return new Promise((resolve) => { if (navigator) { navigator.geolocation.getCurrentPosition( ({ coords }) => { resolve(coords); } ); } else { resolve(null); } }) } I've simplified things a bit here, but the basic structure is the same. We're returning a Promise object, which is basically an IOU. Eventually, it will resolve to some value. Notice that the Promise's resolve function has basically replaced our onDone from before. Under the hood, Promises are built on callbacks. But a Promise let's us do neat tricks like this: async function logLoc() { let loc = await getLocation(); console.log(loc); } logLoc(); This async function will pause its execution until the Promise we returned resolves. The resulting code looks almost synchronous.
2 of 3
1
export async function getLocation({ enableHighAccuracy, maximumAge, timeout } = {}) { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy, maximumAge, timeout }); }); } const { coords } = await getLocation(); That's roughly my solution, though I also added support for AbortSignal, which is not important here. The problem you're having is that your callback to getCurrentPosition() isn't being called immediately so isn't updating the loc variable until much later.
Top answer
1 of 3
10
This is a question of scope. And, it's not that functions are localized. The correct statement is: Variables named within a function are localized. (See http://www.w3schools.com/js/js_scope.asp. ) Browsers that read JavaScript read it like human beings: from left to right and from top to bottom in that order. Instead of thinking about variables and words like “override,” think of a variable like a newly created sticker after we define it (or give it a value). As we read the script from left to right and top to bottom, imagine placing the sticker on our favorite notepad. The first sticker has the name of Andrew. When we call (or invoke) the function with command createFullName("Joel", "Kraft"), this is when we enter the function to find yet another sticker with the name “Joel Kraft” (name = fName + " " + lName;). In this instance, we place the sticker “Joel Kraft” over initial sticker “Andrew”. We can now only see Joel Kraft on the notebook. We continue to read through the function from left to right and top bottom until we complete all of the function’s instructions. Here is your example script in real-time: http://codepen.io/webdesignertroy/pen/ZBvzwm In this CodePen, comment out line 5 in the JS to witness the order of operations the browser is utilizing. When you comment out line 5, you get the name Andrew. This shows that Andrew was written to the DOM first before it was overwritten by the function and its local variable, called afterwards.
2 of 3
5
But if you use the "var" keyword in function it give you the same result like with the "const" and in global scope the variable name has value = "Andrew".
🌐
Hostman
hostman.com › tutorials › understanding global variables in javascript
Understanding Global Variables in JavaScript | Hostman
December 26, 2025 - This example also shows that you ... the function. ... The let and const keywords can also be used in declaring global variables in JS. ... Note: Variables declared using let can have their values changed, whereas constants declared with const cannot be reassigned. ... It's important to pay attention to best practices while using global variables in JavaScript in order to ...
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
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
JavaScript (programming l... ... 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.
🌐
Broadcom
techdocs.broadcom.com › us › en › ca-enterprise-software › intelligent-automation › ca-workload-automation-de › 25-0 › scheduling › using-javascript › Global-Variables › Modify-a-Global-Variable.html
Modify a Global Variable - Broadcom TechDocs
July 17, 2025 - You can modify an existing global variable in a JavaScript script if you need to change the variable's details. To modify a global variable, use the setVar function.
🌐
Quora
quora.com › Can-you-change-a-global-variable-in-a-function
Can you change a global variable in a function? - Quora
Answer (1 of 2): If you’re talking about Python you can only do that when you declare them as global in the function! However, you can still change the elements of a global list, even if you did not declare the list as global in the function!