A semi-functional javascript program that presents quiz questions in a popup window.
<button id="startButton">Start</button>
<pre id="log"></pre>
<script>
//Create constants to store elements for button and text field
const startButton = document.querySelector("#startButton");
const log = document.querySelector("#log");
startButton.addEventListener("click", () => {
//initialize score variable to 0
var score = 0;
//create a for loop using a counter from 0 to 5 to cover the array positions of each array
for (i=0; i<5; i++){
score = score + triviaQuiz(i);
}
log.innerText="Your score is " + score;
});
</script>
//create an array of at least 3 trivia questions
var triviaArray = ['tcp port for SSH','tcp port for telnet','tcp port for SMTP','tcp port for DNS','tcp port for HTTP '];
//create an array with answers to the trivia questions
var answerArray = ['22','23','25','53','80'];
//create quiz function that accepts one parameter which is the array position counter
function triviaQuiz(i){
//set points and guesses to 3 each time the function is called
var points=3;
var guesses=3;
while (guesses > 0){
ans = prompt("what is " + triviaArray[i]);
//ask question i and store result in ans
//note i comes in as arg from a loop external to the function
//compare ans to corresponding position in answer array
if(ans==answerArray[i])
{
alert("correct");
//guesses=0;
return points;
//if correct, exit the function now and return points
}//endif
else{
alert("incorrect");
guesses = guesses-1;
points = points-1;
//if incorrect, subtract 1 each from guesses and points
}//endelse
}//end while
return 0; //if no correct answers given during while loop, return 0
}//end function