This is a true or false quiz. I need the score for the final answer to be updated before the alerts display either the winning or losing alerts.
The below code results in 9 of the 10 scores being updated. After the 10th question is answered the quiz goes straight to the alerts then upon closing the alert the game restarts. When I've commented out from 'else { endGame() } }' to the end of the restartGame function, I can see the last score updates. I'm unsure where to take it from here. GitHub link can be provided. Thanks in advance!
function loadQuestion() {
const currentQuestion = questionsAnswers[questionIndex];
document.getElementById("question-box").innerHTML = currentQuestion.question;
}
let correctScore = 0;
let incorrectScore = 0;
function checkAnswer() {
const currentQuestion = questionsAnswers[questionIndex];
const correctAnswer = currentQuestion.correctAnswer;
console.log(correctAnswer)
if (userAnswer === correctAnswer) {
console.log(questionsAnswers[questionIndex]);
correctScore++;
}
if (userAnswer != correctAnswer) {
console.log(questionsAnswers[questionIndex]);
incorrectScore++;
}
document.getElementById("correct-score").textContent = correctScore;
document.getElementById("incorrect-score").textContent = incorrectScore;
questionIndex++;
if (questionIndex < questionsAnswers.length) {
loadQuestion();
} else {
endGame()
}
}
//once all ten questions have been answered the player is told if won or lost and invited to play again
function endGame() {
if (correctScore === 10) {
alert("Congratulations - you won!")
} else {
alert("Unlucky, you didn't win this time - play again!")
}
restartGame()
}
function restartGame() {
questionIndex = 0;
correctScore = 0;
incorrectScore = 0;
document.getElementById("correct-score").textContent = correctScore;
document.getElementById("incorrect-score").textContent = incorrectScore;
loadQuestion();
}
<div>HTML Here please!</div>
questionIndex
seems to be undefined here.