How to alter the JavaScript code below so that it can avoid exposing the variables and functions to the global scope?
var nMax = 10;
var i = 0;
var step = function(){
//do stuff
i += 1;
if(i < nMax){
step();
}else{
alert('finished');
}
}
step();
Ideally it would be grateful if the reason behind it could be provided.
Any idea would be very much appreciated!
Just wrap it in an anonymous function, and call that function immediately:
Another Example: http://jsfiddle.net/n5Srd/