I'm wondering why I have to use the variable keepScore to make my code works.
After delete var I would write:
questions[n].checkAnswer(parseInt(answer), score())
but then point amount could be only 0 or 1 - var sc=0 execute every cycle.
Then what is the difference between these two codes?
function score() {
var sc = 0;
return function (correct) {
if (correct) sc++;
return sc;
}
}
var keepScore = score(); //here
function nextQuestion() {
var n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer.');
if (answer !== 'exit') {
questions[n].checkAnswer(parseInt(answer), keepScore); //here
nextQuestion();
}
}
Your function
scoreis a function that returns a function. The outer function's variables are baked into the inner function (this is called a closure). The purpose of doing that here is to allow the variablescto be used by the inner function but not be available to other functions. It is essentially a way to hide that variable. This is a common JavaScript idiom (you can use it in other languages, but I see it a lot more in JavaScript than in any other languageāin fact, there's a related pattern given a special name: the immediately-invoked function expression).The variable
keepScoreholds a reference to the function thatscore()returns, so when you callkeepScoreyou are really calling that function. Since you only callscore()once,scis initialized to zero only once, andkeepScore()increments it.I have to wonder... if you don't know what it's doing, why did you write it that way?