silent_john
silent_john

Reputation: 17

Understanding Private Variables (Closure?) in Javascript with specific example

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++;
    }
};

Upvotes: 1

Views: 471

Answers (1)

Bwaxxlo
Bwaxxlo

Reputation: 1880

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.

Upvotes: 2

Related Questions