6

If I include a JavaScript file in my HTML page, do the variables declared in my JavaScript file also have scope in my <script /> tags in my HTML page? For example, in my included JS file, I declare a variable:

var myVar = "test";

Then inside my HTML page, what will this produce (if it's after my include script tag)?

alert(myVar);

3 Answers 3

15

If you declare the variable outside of any function as

var myVar = 'test';

or at any location as

myVar = 'test';

or

window.myVar = 'test';

It should be added to the Global Object (window) and be available anywhere as

alert(myVar);

or

alert(window.myVar);

or

alert(window['myVar']);
Sign up to request clarification or add additional context in comments.

3 Comments

Even with an included JavaScript file?
Yup. Try it out: test.html: <html> <head> <script type=text/javascript src=test.js></script> </head> <body onload="alert(test);"> </body> </html> test.js: var test = 'hello!'; put those two files in the same folder and load the html page. it works!
hmm that didn't format very nicely, but i hope you get the idea.
3

It will produce an alert containing "test".

All variables declared at the top level in JavaScript share the same scope. If you want to use variables in one file that won't clash with another, then you can use an anonymous function to introduce a new scope:

var myVar = "something else";
(function () {var myVar = "test"; alert(myVar)})();
alert(myVar);

edit: As BYK points out, you can expand this into something that resembles a full fledged namespace, by assigning an object literal:

var MyNamespace = (function () {
  var myVar = "something";
  return { alert: function() { alert(myVar) },
           setVar: function(value) { myVar = value } }
})();

1 Comment

You can also use a "namespace" which simply is a static Object for grouping your variables and functions.
1

When you declare a variable or a function in your code, you're creating a property of window. Consider these examples:

var a = 'Cow';
alert(window.a); // Cow
alert(this.a); // Cow
alert(a); // Cow

If you declare a variable inside a function, your variable won't be accessible from outside of it unless you add it to the window object:

function lalala() {
    alert(a); // still Cow
    a = 'Pig'; // We're tired of cows by now. Let's make it a pig.
    var b = 'Sheep';
}
lalala();
alert(a); // Pig
alert(b); // undefined, since b is declared in the lalala scope

Thus, your example would alert test.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.