Benjistep
Benjistep

Reputation: 25

How to store variables correctly without storing them globally?

Suppose I declare a variable called foo in the ready function. Normally, locally declared variables are deleted when the function ends right?

I want to use this variable in the event listener of #someid. I tried this and the foo variable is still accessible when a click-event occurs on #someid.

Why isn't this variable destroyed and still accessible, when the ready function ends? Is it safe to declare a variable and use it this way? I don't want to declare the variable globally, as I didn't.

EDIT: Where are these event listeners and their variables stored?

Here is my js:

$(document).ready(function() {
var foo = 0;

//random event listener
$('#someId').on('click', function() { foo++; }); //increment foo

});

Upvotes: 1

Views: 66

Answers (1)

Jamiec
Jamiec

Reputation: 136104

I want to use this variable in the event listener of '#someid'. I tried this and the foo variable is still accessible when a click-event occurs on '#someid'.

This is correct, your variable foo is still in scope, and therefore accessible.

Why isn't this variable destroyed and still accessible?

Because both are in the scope of the ready function.

I don't want to declare the variable globally.

You haven't, so don't worry. You have declared a variable which is local to the ready function, and not global.

Upvotes: 5

Related Questions