Can I access variables from another file?

JavascriptScope

Javascript Problem Overview


Is it possible to use a variable in a file called first.js inside another file called second.js?

first.js contains a variable called colorcodes.

Javascript Solutions


Solution 1 - Javascript

As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window or (in the global scope) this to get the same effect.

// first.js
var colorCodes = {
  back  : "#fff",
  front : "#888",
  side  : "#369"
};

... in another file ...

// second.js
alert(colorCodes.back); // alerts `#fff`

... in your html file ...

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

Solution 2 - Javascript

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN

Solution 3 - Javascript

Using Node.js you can export the variable via module.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

Then, import the module/variable in second file using require.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.

Solution 4 - Javascript

I did like the answer above said, but it didn't work for me at first because I was declaring these variables inside jQuery $( document ).ready().

So make sure you declare your variables inside the <script> tag not somewhere else.

Solution 5 - Javascript

This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)

Solution 6 - Javascript

I came across amplify.js. It's really simple to use. To store a value, let's call it "myValue", you do:

amplify.store("myKey", "myValue")

And to access it, you do

amplify.store("myKey")

Solution 7 - Javascript

If you store your colorcodes in a global variable you should be able to access it from either javascript file.

Solution 8 - Javascript

I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSAKView Question on Stackoverflow
Solution 1 - JavascriptDagg NabbitView Answer on Stackoverflow
Solution 2 - JavascriptGerma VinsmokeView Answer on Stackoverflow
Solution 3 - JavascriptXintonView Answer on Stackoverflow
Solution 4 - JavascriptBasheer AL-MOMANIView Answer on Stackoverflow
Solution 5 - JavascriptPiskvor left the buildingView Answer on Stackoverflow
Solution 6 - JavascriptBen LeitnerView Answer on Stackoverflow
Solution 7 - JavascriptFerminView Answer on Stackoverflow
Solution 8 - JavascriptAlanView Answer on Stackoverflow