variables defined globally

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
pirelouit
Posts: 18
Joined: January 16th, 2006, 12:08 pm

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
byronnash
Posts: 321
Joined: July 7th, 2004, 2:30 pm
Location: Charlotte, NC
Contact:

If I am not mistaken, putting { } brackets around your script will contain those variables to just that execution.
vidpat
Posts: 86
Joined: October 21st, 2004, 12:36 am
Location: Phoenix, AZ
Contact:

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.
davestewart
Posts: 114
Joined: March 10th, 2005, 5:50 am
Location: London, UK
Contact:

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.
Post Reply