Forum Discussion

michaela's avatar
12 years ago

Nested functions and variables

Hi,



It took me some hours to figure out why my script did all kinds of stupid things - but it came down to this:



function Test1()

{

  var counter=mylist1.Items.Count;

  for(r=1;r<=counter;r++)

  {

     var findme="Test"+r;

     Test2(findme);

  }

}



function Test2(mytext)

{

  var counter=mylist2.Items.Count;

  for(r=1;r<=counter;r++)

  {

      // do stuff

  }

}



Basically, what I found is that changes to the loop variable "r" in Test2 also affect "r" in Test1.

This behaviour is not quite what I expected - even from a simple scripting language ...



How do I prevent that from happening other than constantly keeping track of  potentially nested loops?

All I found in the tutorials is how to make variables globally accessible but not how to restrict them to a "private" level.



tia

1 Reply

  • AlexKaras's avatar
    AlexKaras
    Champion Level 3
    Hi Julia,



    Why not to declare counter variable like you do it for other variables for your code snippet?

    Variables declaration is one of the best practices that helps to prevent cases like yours...