207

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.

Right leg
  • 13,581
  • 5
  • 36
  • 68
SAK
  • 3,270
  • 7
  • 24
  • 38
  • @Roki: For example, you could be loading data from another website, while the script to process them is on your site: `` – Piskvor left the building Jul 14 '10 at 08:23
  • the datasource site don't have a callback? what i mean: download second.js contains: ... function secondscriptFn(o) { //do something /w data; } ... download http://datasource.example.net/first.js?callback=secondscriptFn then first contain: secondscriptFn({back:"#fff",front:"#888",side:"#369"}); more controllable and robust than global scope versions, because you can control the first.js scope... – Roki Jul 14 '10 at 08:43
  • 4
    Just as a note if you are using jQuery and you are trying to do this. You need to make sure that you don't put the variable that you trying to access from the first file in the '$(document).ready()' function; otherwise it won't load properly, at least from my experience. – Collin McGuire Dec 13 '13 at 23:44

9 Answers9

231

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> 
Dagg Nabbit
  • 68,162
  • 17
  • 100
  • 136
  • 7
    In a browser, `window` *is* the global scope - so window.colorCodes and the (global) object colorCodes is the same object. – Piskvor left the building Jul 14 '10 at 08:22
  • True... the reason I mention it is for cases where you need to set a global variable from a non-global scope. – Dagg Nabbit Jul 14 '10 at 08:28
  • 3
    what about html? in html I have: ` ` will first.js see that variable? I tested it in Google Chrome extension and it didn't work – user25 Jun 10 '18 at 19:04
  • @user25, I have the same problem, did you find a solution ? – Mercury Jul 24 '18 at 10:10
  • 2
    If you are using eslint, you can add `/* global colorCodes */` on the line above to prevent "...is not defined" error message – Joseph K. Jan 20 '19 at 22:59
  • @user25 and Mercury code in first.js can access variables defined at the global scope level in HTML from within the script tag. This may not be the case for Google Chrome extensions which is out of the boundaries of this SO question. – Mike Kormendy Jul 05 '19 at 20:55
  • This is an outdated answer. Please accept my answer below that uses ES6 export/import syntax, which is mostly the standard now. – Gal Grünfeld Dec 26 '20 at 11:42
65

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

Germa Vinsmoke
  • 2,640
  • 3
  • 15
  • 28
  • `const` in the example and talking about `variable` - am I missing something? If I do this and use a variable `var` and try to assign then at least in a Chrome extension it complains with "Cannot set property XXX of # which has only a getter". If this can only be done with `const`/read-only, then this is a highly misleading answer. – AntonOfTheWoods Jan 04 '21 at 07:19
15

I did like what answer above said but although, it didn't worked with me

because I was declaring these variables inside JQuery $( document ).ready()

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

Community
  • 1
  • 1
Basheer AL-MOMANI
  • 11,997
  • 8
  • 79
  • 85
13

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)

Piskvor left the building
  • 87,797
  • 43
  • 170
  • 220
  • 1
    You may need to attach that variable to the object like: this.colors = colors. If its an object rather than an enum, you can make a function to just return the value. this.getTextColor = function() { return colors.text; }; – aggaton Jan 20 '13 at 21:02
  • 1
    how would you update a variable from a loaded page? doesn't seem to work. – v3nt Jun 21 '16 at 16:26
12

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.

Xinton
  • 139
  • 1
  • 6
4

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")
Ben Leitner
  • 1,512
  • 1
  • 10
  • 32
2

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

Fermin
  • 32,216
  • 20
  • 81
  • 125
2

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.

Alan
  • 317
  • 2
  • 5
1

This is quite an old question, but I'm going to provide a modern solution that's been available since ES6 - export and import:

In first.js:

let colorcodes = <whatever>;
export default colorcodes //or a different export statement

In second.js:

import colorcodes from <path-to-first.js> //or a matching import statement
Gal Grünfeld
  • 610
  • 2
  • 7
  • 25
  • I like your approach, but what if I want to export multiple variables? Do I still have to write an export statement for every variable? – Zaid Dec 31 '20 at 19:37
  • 1
    Check out the [MDN `export` documentation syntax](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) (already linked in the original comment). – Gal Grünfeld Jan 02 '21 at 12:02
  • Can you have multiple default exports? Or do I need to have a separate module for every variable I want to share? – AntonOfTheWoods Jan 04 '21 at 07:22
  • @AntonOfTheWoods you can't have multiple `export default` in the same file, but you can have multiple `export`. Note, they are imported slightly differently: `import { colorcodes } from `. This is explained in the first section of the documentation linked in this answer an the comment above. – ajbeaven Jan 26 '21 at 03:54
  • @ajbeaven, actually my problem was that I was looking for python module variables, which are not read-only like in JS. Accessors work fine though. Here I was thinking it was possible to assign directly to default exports. I had already found you couldn't assign to non-default exports, and I was reading it that you could to default exports, but that would mean a single variable per file. Accessors work just fine. – AntonOfTheWoods Jan 27 '21 at 04:19