OK, I have tried to use a closure to no avail on the following code to keep a variable private. I am brand new to javascript and have read a number of posts about closures and can still not wrap my head around them. Below, I have a function that, upon each press of a particular button, displays the next word in an array. I want my counter variable ("whatNumber" below) that I am using in this function to not be global but I cannot figure out how. Here is my simple code:
var wordList = ["jumper", "stumpy", "smelly gumdrops", "awesome puttputt", "soilent green"];
var whatNumber = 0;
function changeWord(){
if (whatNumber < wordList.length) {
alert(wordList[whatNumber]);
whatNumber++;
}
};
changeWordroutine in an IIFE ((function() { ... })()) and declare your variable inside that. Return the function from inside the IIFE.