var foo = 10; vs. window.foo = 10;

P

petermichaux

Hi,

I've wondered for a what the differences between the following.
<script type="text/javascript">
var foo = 10;
</script>

<script type="text/javascript">
window.foo = 10;
</script>

For one, I think I can do

delete window.foo;

The reason I ask is avoiding garbage collection. If I have an event
handler function for onload that declares some global object that I
want to persist I would like to avoid doing this in the head element.

<script type="text/javascript">
var foo;
function handleLoad(e) {
foo = {bar: 45};
};
</script>

I would rather have just the following if it will serve my needs as it
seems more self contained

<script type="text/javascript">
function handleLoad(e) {
window.foo = {bar: 45};
};
</script>

Thank you,
Peter
 
B

Benjamin

We prefer the declaring of a global varible outside a function so it's
easier to understand and read. However, remeber that for self
containment reasons use of global varibles should be minimized.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top