Forum Moderators: open

Message Too Old, No Replies

Using var to initiate variables?

         

benj0323

3:35 am on Jul 9, 2005 (gmt 0)

10+ Year Member



I've always been very confused as to when to use var and how to use it. I know if I want the variable to stay within the scope of a function I should initiate it with "var", but how do I do this?

Let's say the first time I use the variable is in a loop. Is it correct to do:

for(var i=0;i<10;i++)
{
var someVar += 'hey'+i;
}

or should i do this:

var someVar = null;

for(var i=0;i<10;i++)
{
var someVar += 'hey'+i;
}

Also what if I do this:

if(someVar)
var anotherVar;

var anotherVar

Because, what if that if statement evaluates false and doesn't even get to the var. Should I do var afterwards jsut incase?

Thanks a lot for your help.

Rambo Tribble

12:59 pm on Jul 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You should initialize a variable that is going to be repeatedly used within a for loop outside the loop. Otherwise, the variable will be reinitialized with each loop, wiping out any data stored in the variable in the previous iteration.

If you want a variable's initialization to be conditional, put it in a conditional statement; if you don't want its initialization to be conditional, don't.