Reputation: 1147
I have the below code to work with:
function loopingFunction(){
if(typeof(foo)=="undefined"){
var foo = 0;
}
alert(foo);
if(foo==0){
// some codes here
}
foo++;
}
The loopingFunction gets called multiple times, and each time my variable foo remains the same..somehow it is lost when i try to increment it
The counter does not seem to work which would increment the var foo each time the function is called..
Is there any workaround for this? Any help would much be appreciated..
FYI i cannot make foo global, i have to find a workaround using closure..
Upvotes: 0
Views: 42
Reputation: 943939
You declare foo
inside the function. It is scoped to that function. Every time the function is called, you create a new variable called foo
.
Declare it outside if you want to reuse the same variable.
var foo;
function loopingFunction() {
if (typeof foo === "undefined") {
foo = 0;
}
alert(foo);
if (foo == 0) {
// some codes here
}
foo++;
}
loopingFunction();
loopingFunction();
loopingFunction();
You could perform all your initialisation outside the loop too to simply things.
var foo = 0;
function loopingFunction() {
alert(foo);
if (foo == 0) {
// some codes here
// … these could probably be moved outside the function too
}
foo++;
}
loopingFunction();
loopingFunction();
loopingFunction();
If you want to keep foo
from being global you can use a closure:
var loopingFunction = function() {
var foo = 0;
function loopingFunction() {
alert(foo);
if (foo == 0) {
// some codes here
// … these could probably be moved outside the function too
}
foo++;
}
return loopingFunction;
}();
loopingFunction();
loopingFunction();
loopingFunction();
Upvotes: 2
Reputation: 15393
You declared foo variable is local make it as global variable.
var foo;
function loopingFunction(){
if(typeof(foo)=="undefined"){
foo = 0;
}
if(!foo){
// some codes here
}
foo++;
}
Upvotes: 0
Reputation: 22158
You are declarating local variable. You must to initialize as global by two ways:
var foo = 0;
function looping....
if(typeof(foo)=="undefined"){
foo = 0; // without var is global
}
Upvotes: 0