Click to See Complete Forum and Search --> : global variable


glotsa
02-13-2003, 08:40 PM
<SCRIPT language="JavaScript">

//initialise the value
var actual = new Array("", "");
var base = new Array("0","1");
var score = new Array("0","0");


function score_cal(index){
....
}

function xxxx(){}

function xyzzz(){}

</SCRPIT>

....

<BODY bgcolor="#cccccc" >
<FORM name="form1" >
.....
</FORM>
</BODY>
*****************************************
In my code, i declare "actual", "base", "score" as global variables. How can i convert it into a function, e.g

function initialize(){
var actual = new Array("", "");
var base = new Array("0","1");
var score = new Array("0","0");
}

so that the form can load it to initialize the variables before calling other functions??

thanks for kindly help :P

AdamBrill
02-13-2003, 09:28 PM
It looks like the function that you made would work fine. You could just have it run it off an onload event. What is wrong with just doing that?

AdamBrill
02-13-2003, 10:48 PM
Dave - does taking out the var before the variable make them global? I was under the impression that all variables are global, is that incorrect?

AdamBrill
02-13-2003, 11:17 PM
Thanks for the explanation... I was goofed up :D

Dan Drillich
02-14-2003, 08:02 AM
What makes this issue confusing is the fact that the var keyword is an optional keyword.
If we declare the following within a function:
var i = 0;
a new variable i will be created in the function, even if there is already a global i.
If we say within the function:
i = 0;
then if a global i exists then 0 is assigned to it. If not, a new local i is created.

khalidali63
02-14-2003, 10:35 AM
Here is my take on this.
:)

//declara a globala variabel
var global;

function test(){
//local variable with var keyword
//if we omit var keyword here local will //have the global scope as well.
var local=0;
glb1=0;
}

so as posted above the scope of a variable is,indeed, determined by the use of var keyword.A variable inside the function with the var keyword is a local variable a variable without var key word inside of a function will have a global scope

cheers

Khalid

Dan Drillich
02-14-2003, 11:29 AM
Dave And Khalid,

You are both absolutely right!

I put it for myself in my own words (if it helps anybody) -

1) A variable defined inside a function without var is in the global scope.
2) var inside a function makes the variable local.
3) Outside a function var has no impact on the scope of the variable.

Thanks,
Dan