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
dharemshpatelAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ALNMOOCommented:
Any variable inside a function with var keyword will be a local variable & if it is without var, it will have a global variable
0
dharemshpatelAuthor 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.
0
ALNMOOCommented:
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

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hieloCommented:
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>
0
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.