Page 1 of 1

variables defined globally

Posted: January 26th, 2006, 7:35 am
by pirelouit
Hi! I was wondering, since variables are defined globally and are even persistent after a script has executed, was is the point of passing parameters to functions (they will have access to the variables anyways)?

Also, is there a way to 'reset' all variables (I mean removing them completely from memory without quitting the application)? Would the garbage function do that?

Thanks

Posted: January 26th, 2006, 8:00 am
by byronnash
If I am not mistaken, putting { } brackets around your script will contain those variables to just that execution.

Posted: January 26th, 2006, 2:30 pm
by vidpat
A compound statement (putting braces around a block of code) does not limit the scope of variables in JavaScript, as it does in most languages. Only function (object) definitions limit the scope of variables declared within them. Of course, closures can be formed, too.

Garbage collection won't erase the globally declared variables, either. It will only delete (deallocate) objects that are no longer referenced. A variable's storage space doesn't constitute such an object, though the memory for any object referenced by a global variable can be freed.

So, unfortunately, to reset globally declared variables, the application would need to be relaunched. Theoretically, when a script is done, it could set all of its global variables to null. There probably is no way to reset them to undefined. (See also the related discussion about const in http://www.aenhancers.com/viewtopic.php?t=223).

One advantage of passing values as parameters is that you don't need to declare everything in the global scope. It is also useful for libraries, calling functions repeatedly with different arguments, and recursive functions all of which contribute to better code design and maintainability.

Posted: January 26th, 2006, 3:59 pm
by davestewart
Also, you could create a generic Object object, and assign variables (properties) to that if you want limit the scope.

vars=new Object()

vars.foo=10
vars.bar="Hello"

But creating functions is really the best way to do things, as variables live and die with the function call.