We help IT Professionals succeed at work.

How to declare a javascript variable as global

I want to declare few javascript variales as global in one js file and would like to use them in another js file's function
Comment
Watch Question

Commented:
Any variable inside a function with var keyword will be a local variable & if it is without var, it will have a global variable

Author

Commented:
I have tried the same,

I have defined strVal= 'test' in one js file
and tried to alert the same in another js file (note: i have included the first js file in second). Still it doesn't work.
Commented:
If you can post your JS test code it will be better. or try this code, it should work.



function myfunction1()
{
txt = 'Global Var';
 
}
 
 
function myfunction()
{
alert(txt);
 
}

Open in new window

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
Any variable declared outside a function is global. From within functions, you have access to these variables if:
1. you do not declare a variable with the same name prefixed with "var"
2. none of the functions parameters is named the same as the "global" variable in question

>>note: i have included the first js file in second
How are you doing the including?  Order matters. Here are a couple of examples:

//file1.js
var msg = "Hello World";

//file2.js
function report()
{
  alert( msg );
}
report();

//test_a.html: This will work
<html>
<head>
 <script src="file1.js" type="text/javascript"></script>
 <script src="file2.js" type="text/javascript"></script>
</head>
<body></body>
</html>

//test_b.html: This will NOT work. Why? When file2.js is included, msg does not exist yet!
<html>
<head>
 <script src="file2.js" type="text/javascript"></script>
 <script src="file1.js" type="text/javascript"></script>
</head>
<body></body>
</html>
Forced accept.

Computer101
EE Admin

Explore More ContentExplore courses, solutions, and other research materials related to this topic.