Search code examples
javascriptfilevar

In Javascript, is there a way to call a var in another .js file like in Java?


In Java if I wanna call a var from another file in the same folder I can just call the file name and then the var I wanna call. But, I'm looking for a similar thing in Javascript. Please let me know if there is. For Example:

FileName: wordBank.java

int wordCount = 0;

Then in the Other File I can call that wordCount by saying:

wordBank.wordCount = 1; // (assuming wordCount is public)

So is there a way to mimic this code in Javascript?


Solution

  • You have to explicitly export and import it like so with es6 wordBank.js:

    export const wordCount = 0;
    

    otherFile.js:

    import { wordCount } from "./wordBank"
    console.log(wordCount)
    

    However, there is no specific way to outright mutate a variable passes between files. You could do something like this:

    let wordCount = 0;
    export function setWordCount(value) {
        wordCount = value
    }
    

    then in the other file:

    import { setWordCount } from "./wordBank"
    
    setWordCount(1)