How to change variables across different modules or js files?

I am in the process of seperating my code so it is more clean. I have started doing this by putting my functions in their respective module. So instead of keeping it in the "index.js", I am keeping it in "change.js" (example name). Here is my function:

let number = 5;

function change(){
    number = number + 1;
}

The problem is, when I put this function in its own respective module called "change.js", when it is called, it gives the error that the variable "number" is not declared. If I then declare it in the "change.js" file, the variable "number" only changes in that file and not in "index.js". Is there anyway to change it in both files, or transfer the value from "change.js" to "index.js"?

5 thoughts on “How to change variables across different modules or js files?”

  1. Before I proceed to my answer this is how I exported and imported:

    const change = require("./change");   //in index.js
    
    module.exports {change); // in change.js
    

    I found something that would make it work:

    //in index.js & "number" and const "change" declared beforehand
    number = change.change(number);
    
    //in change.js
    function change(number) {
        return number + 1;
    }
    //module.exports down here
    

    This would then change the variable "number" in the index.js with the function "change" running from module "change.js"!

    Reply
  2. Your change.js file should look something like this:

    let number = 5;
    
    const change = () => number = number + 1;
    
    export { number, change }
    

    And then, on your index.js you can import the variable as

    import { number, change } from './change.js';
    ...
    
    Reply

Leave a Comment