If I change a value of a variable, will it update in a file that exported it?

Gaurav Dixit
Oct 16, 2023 08:04 PM 1 Answers
Member Since Mar 2022
Subscribed Subscribe Not subscribe

Let's say I we have the file main.js with the following code:

var count = 0
function increase(){
    count = count + 1
export default count

In which the function increase() is called when a button is clicked.

Now if we import the variable count from a different file, let's say index.js. After that we press the button. Will the value in index.js update? and if no then how to do so?

0 Subscribers
Submit Answer
Please login to submit answer.
1 Answers
Sort By:
Best Answer
Oct 16, 2023

In the code you've provided, you are exporting a variable called count from the main.js file. However, exporting a variable like this doesn't create a live link between the exported variable and the original variable in the main.js file. Instead, it essentially exports the current value of count at the time of the export. This means that when you import the count variable into index.js, it holds the current value of count at the time of the import.

If you later modify the count variable in the main.js file, it won't automatically update the value of count in index.js. The imported count variable in index.js becomes a copy of the original value, not a reference to it.

To achieve live updates to the imported variable in index.js when the button is clicked in main.js, you can use a different approach by exporting and importing a function that returns the updated value:


var count = 0;

function increase() {
count = count + 1;

export function getCount() {
return count;

Save to grepper


import { getCount } from './main.js';

// You can now get the current count value by calling getCount()
// For example, you can set up an event listener to update the count when the button is clicked.
document.getElementById('button').addEventListener('click', () => {
const currentCount = getCount();
console.log(currentCount); // This will log the updated count.

Save to grepper

By exporting a function getCount that returns the current value of count, you can retrieve the latest value in index.js whenever you call getCount(). This way, you can have a live connection to the count variable in main.js and get updates when the increase function is called.

Sign in to Reply
Replying as Submit