Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML JavaScript Include File Variable Scope

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);
like image 894
Brandon Montgomery Avatar asked Apr 15 '09 14:04

Brandon Montgomery


1 Answers

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']);
like image 175
James Orr Avatar answered Sep 22 '22 14:09

James Orr