I have the following code I need some clarification with. I want to understand it perfectly before I move on. I know the example might be silly and I am sure there is a lot of better ways to solve the problem but for the sake of this lesson the person used this example.
All I need is some clarification on how exactly the flow of the score function works and onwards. Where are the values coming from? How is it adding up each time the person gives the right answer?
I basically want to understand how this code generates the number to display to the console every time the user inputs a true value into the alert. I am sorry if I'm not coming through clearly, I just need to understand how the code works from function score() and onwards. I could not for the life of me figure it out. Where is sc getting its values from, and where does it pass it too and; and; and.
Is there anyone that's willing to give me a layout of how this code fits together. I would be eternally grateful.
(function() {
function Question(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
Question.prototype.displayQuestion = function() {
console.log(this.question);
for (var i = 0; i < this.answers.length; i++) {
console.log(i + ': ' + this.answers[i]);
}
}
Question.prototype.checkAnswer = function(ans, callback) {
var sc;
if (ans === this.correct) {
console.log('Correct answer!');
sc = callback(true);
} else {
console.log('Wrong answer. Try again :)');
sc = callback(false);
}
this.displayScore(sc);
}
Question.prototype.displayScore = function(score) {
console.log('Your current score is: ' + score);
console.log('------------------------------');
}
var q1 = new Question('Is JavaScript the coolest programming language in the world?',
['Yes', 'No'],
0);
var q2 = new Question('What is the name of this course\'s teacher?',
['John', 'Micheal', 'Jonas'],
2);
var q3 = new Question('What does best describe coding?',
['Boring', 'Hard', 'Fun', 'Tediuos'],
2);
var questions = [q1, q2, q3];
function score() {
var sc = 0;
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
var keepScore = score();
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);
nextQuestion();
}
}
nextQuestion();
})();