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.