Global variables in Javascript across multiple files

JavascriptScopeGlobal VariablesGlobal

Javascript Problem Overview


A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.

I have attempted to create a global variable by defining:

var myFunctionTag = true;

In global scope both in my HTML code and in helpers.js.

Heres what my html code looks like:

<html>
...
<script type='text/javascript' src='js/helpers.js'></script>	
...
<script>
  var myFunctionTag = false;
  ...
  //I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>

Is what I am trying to do even feasible?

Javascript Solutions


Solution 1 - Javascript

You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.

<script type='text/javascript' > 
  var myFunctionTag = false; 
</script>
<script type='text/javascript' src='js/helpers.js'></script>     
... 
<script type='text/javascript' > 
  // rest of your code, which may depend on helpers.js
</script>

Solution 2 - Javascript

The variable can be declared in the .js file and simply referenced in the HTML file. My version of helpers.js:

var myFunctionWasCalled = false;

function doFoo()
{
    if (!myFunctionWasCalled) {
        alert("doFoo called for the very first time!");
        myFunctionWasCalled = true;
    }
    else {
        alert("doFoo called again");
    }
}

And a page to test it:

<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>

<body>


<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

<script type="text/javascript">doFoo();</script>

<p>Some stuff in between</p>

<script type="text/javascript">doFoo();</script>

<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

</body>
</html>

You'll see the test alert() will display two different things, and the value written to the page will be different the second time.

Solution 3 - Javascript

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?

All the results were as expected.

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.

My example files follow:

EXTERNAL JS:

var global = 0;

function f1()
{
	alert('fired: f1');
	global = 1;
	alert('global changed to 1');
}

function f2()
{
	alert('fired f2');
	alert('value of global: '+global);
}

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

Solution 4 - Javascript

//Javascript file 1

localStorage.setItem('Data',10);

//Javascript file 2

var number=localStorage.getItem('Data');

Don't forget to link your JS files in html :)

Solution 5 - Javascript

Hi to pass values from one js file to another js file we can use Local storage concept

<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>

Two.js file

function myFunction() {
var test =localStorage.name;

 alert(test);
}

Three.js File

localStorage.name = 1;

Solution 6 - Javascript

If you're using node:

  1. Create file to declare value, say it's called values.js:
export let someValues = {
  value1: 0
}

Then just import it as needed at the top of each file it's used in (e.g., file.js):

import { someValues } from './values'

console.log(someValues);

Solution 7 - Javascript

I think you should be using "local storage" rather than global variables.

If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.

I used http://www.jstorage.info/ and I'm happy with it so far.

Solution 8 - Javascript

You can make a json object like:

globalVariable={example_attribute:"SomeValue"}; 

in fileA.js

And access it from fileB.js like: globalVariable.example_attribute

Solution 9 - Javascript

You can set window['yourVariableName'] = yourVariable; and it will make that variable global for all the files.

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
QuestionGoroView Question on Stackoverflow
Solution 1 - JavascripttvanfossonView Answer on Stackoverflow
Solution 2 - JavascriptStephen PView Answer on Stackoverflow
Solution 3 - JavascriptMartinView Answer on Stackoverflow
Solution 4 - JavascriptDhanushView Answer on Stackoverflow
Solution 5 - JavascriptSajithView Answer on Stackoverflow
Solution 6 - JavascriptJared WilberView Answer on Stackoverflow
Solution 7 - Javascriptpaulo62View Answer on Stackoverflow
Solution 8 - JavascriptpartizanosView Answer on Stackoverflow
Solution 9 - JavascriptMrAniView Answer on Stackoverflow