Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global variables in javascript??? 1

Status
Not open for further replies.

kikilo

Programmer
May 30, 2004
4
US
Hi are there such things as global variables in javascript? I need some data from a script that runs under the <BODY> tag for another script that runs under the <HEAD> tag...
 
Any variable declared outside of a function can be considered global.

Adam
while(ignorance){perpetuate(violence,fear,hatred);life=life-1};
 
Hi. To add to what Adam has said that if inside a function you use a variable without "var" it will also become global.

e.g.
function a()
{
count = 0;
}

In the above code the variable "count" will become global. This is a common mistake as I have faced it and a lot of bugs come bcoz of this. So always make sure that u use "var" if you want to make the variable local.
 
Here's a quickie little test:

Code:
<html>
<head>
<script>
var test1var = "test 1";
function alertTestVar()
{
 alert(test1var);
 alert(test2var);
 alert(test3var);
 alert(test4var);
 alert(test5var);
}

function declaresGloballyWithinFunction()
{
 test4var = "test 4";
 var test5var = "test 5";
}
</script>
</head>
<body>
<script>
var test2var = "test 2";
</script>
Hi!
<br />
<input type='button' onclick='alertTestVar()' value='Test' />
<input type='button' onclick='declaresGloballyWithinFunction();alertTestVar()' value='Test Differently' />
<script>
var test3var = "test 3";
</script>
</body>
</html>

Note that hitting the 'Test' button first will lead to an error when it tries to alert the value of test4var since, despite it being global, it is never instantiated or referenced because it is not officially introduced until the function in which it resides has been called.

Pressing 'Test Differently' DOES call that function, so test4var does get instantiated, but when the alert tries to display the value of test5var, it fails. That var has gone out of scope.

Pressing 'Test' again at this point WILL show test4var, since now it has been declared. Of course, the program will still fail when trying to show test5var.

All the other testXvar's are global and referenceable (word?), despite the various places in which they're declared.

'hope that helps!

--Dave
 
Thanks so much for this information and how quickly u responded! Thanks for the script and explanation, I ran it and it works.

:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top