abalter
abalter

Reputation: 10383

How to give access in one Javascript file to a variable defined in another

What is the simplest way to put a variable in one js file in the scope of another js file. The question has been asked before, and answers given. But I'm unsatisfied because (1) The explanations were not simple to me and (2) The solutions were not simple to me. One answer was "As long as the global variable has been put into global scope before it is called by the external script." The OP asked "how do I put the global variable into global scope?", and there was no direct answer.

So, I have:

test1.js

var a = true;

test2.js

alert("a is " + a);
console.log("a is " + a);

and

test.html

<html>
  <body>
    <h1>Test</h1>
  </body>

  <script src="js/test1.js"></script>
  <script src="js/test2.js"></script>
</html>

No alert appears, and the console logs ReferenceError: a is not defined.

What is the simplest way to make the variable a available in test2.js?

Upvotes: 1

Views: 2119

Answers (4)

Maverick
Maverick

Reputation: 4498

Ok, so here is what happened.

There was a glitch in the questioner's editor, which caused the file test1.js to be blank. Hence, the code var a = true never ran.

More details: When everything was fixed up, the code worked as expected. As all of the code is already in the global scope (eg: not inside a function() {}) var a = true declared a global variable called a with the initial value of true.

So long as the code in test1.js was run before test2.js the code worked fine. Keep in mind that this means that the order the code is run in is what makes the difference. In this case, it would only depend on the order the files are listed in the test.html file. That's because even though a browser might asynchronously finish loading test2.js before test1.js has finished, it knows the order the files were specified in and reads the code in that order.

And don't forget kids: global variables are generally bad, if you really feel the need to use them, refactor your code until you change your mind :).

Upvotes: 4

AbsoluteƵER&#216;
AbsoluteƵER&#216;

Reputation: 7880

In Javascript, variables declared outside of a function are Global. In HTML the scope of the Javascript variable is window, if it is global. The var keyword doesn't change whether the variable is a global or not.

When you define a variable inside of a function, that variable is local to the function unless you're assigning it to the window object of the DOM or assigning the value to an already declared global variable.

In the following code we assign a Global variable a and set it to the boolean value true.

We output an alert to show it is true.

Then we fire a function that alters the variable's value to be false.

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript Variable Scope</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            var a = true;

        </script>    
    </head>
    <body>
        <div>TODO write content</div>
        <script type="text/javascript">
            alert('a is '+ a);

            function alterOutput(){
                a = false;
                alert('a is '+ a);
            }

            alterOutput();

            alert('a is '+ a);

        </script>



    </body>
</html>

The reason not to use global variables is because even though the variable is reassigned inside the scope of a function, because it was defined initially as a global variable, the value has been changed.

There is a write-up about Javascript variable scopes on w3schools.

When you're loading separate Javascript files the browser loads these files non-sequentially if not asynchronously. You would need to check that the first script has loaded prior to firing your dependent code.

You might even want to consider requiring the other file.

What is the simplest way to make the variable a available in test2.js?

The simplest way to make a available is to define it in the HTML header's script tag. You could also define it in test2.js for simplicity as well.

Upvotes: 0

Marco Bernardini
Marco Bernardini

Reputation: 705

What is the simplest way to make the variable a available in test2.js?

Here is the simplest way I actually use.

In the HTML:

<div id="something" data-var="blank">

test1.js

 document.getElementById('something').dataset.var = 'true';

test2.js

var a = document.getElementById('something').dataset.var;
alert("a is " + a);
console.log("a is " + a);

Your variable is "glued" to the page, so it is available to every js you can load. Think to an <input type="hidden">, but more hidden.

Maybe it is not the most elegant solution, but surely it's easy, specially if you have a hundred divs in a page and don't want to deal with bulky Object to store all the values.

My hundreds of data- are created by an Ajax call, getting a template from a php include file and filling the blanks: I use them to restore fields edited by the users to their original value.

Upvotes: -1

Adrian
Adrian

Reputation: 46442

Removing the var generally makes variables global. "Global" in the case of browser-based JavaScript, however, just means "window", so setting window.myVar = "something" has the same effect as myVar = "something" without the var on it.

Upvotes: 0

Related Questions