1

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++;
    }
};
2
  • Wrap the changeWord routine in an IIFE ((function() { ... })()) and declare your variable inside that. Return the function from inside the IIFE. Commented Jul 16, 2015 at 12:44
  • IIFE = Imediate Inkoked Function Expression Commented Jul 16, 2015 at 13:03

1 Answer 1

2
function changeWord(){
    var wordList = ["jumper", "stumpy", "smelly gumdrops", "awesome puttputt", "soilent green"];
    var whatNumber = 0;
    return function alertWord(){
        if (whatNumber < wordList.length) {
            alert(wordList[whatNumber]);
            whatNumber++;
        }
    }
};
//to run this
var alertNewWord = changeWord();
alertNewWord() //jumper
alertNewWord() //stumpy

This comes with a bonus of being able to have different functions having different levels of alerting. e.g: if you do another var anotherAlertFn = changeWord() and you call anotherAlertFn() it will result in "jumper". The initial functions (i.e: alertNewWord()) will still have it's own state, i.e: whatNumber === 3 while anotherAlertFn has whatNumber === 1. This can be very useful, imagine a function keeping score for different players in a game. Every player can use the same function without being able to cheat (i.e: change their score) and never affecting other players' scores.

Sign up to request clarification or add additional context in comments.

4 Comments

OK that works perfectly! I am going to study this. Since I know exactly what it does I should be able to start to figure out closures. Thanks so much!
@silent_john check my edit with further explanation on closures.
Wow, this is great. To help motivate me to learn javascript, my first project is actually a word game like catchphrase! So your hypothetical example of points will be perfect too. Thanks again!
@silent_john checkout a small "Guess the Number" game I made a while back. It uses the same concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.