This is JS:
function Question(question, answers, correct) {
this.question=question;
this.answers=answers;
this.correct=correct;
}
Question.prototype.displayQuestion=function () {
console.log(this.question)
this.answers.forEach((answer, i)=> {
console.log(`${i}: ${answer}`)
})
}
Question.prototype.checkAnswer=function(answer) {
(answer==this.correct)? true: false
}
var q1=new Question("What day is it today?", ["Monday", "Tuesday"], 0)
var q2=new Question("How are you?", ["Good", "Really good"], 1)
var q3=new Question("Is it nice out?", ["Yes", "No", "In-between"], 3)
var questions=[q1, q2, q3];
function createGame() {
var num=Math.floor(Math.random()*questions.length)
questions[num].displayQuestion()
var userInput=parseInt(prompt("Please enter answer"))
questions[num].checkAnswer(userInput)? console.log('You won!'): createGame()
}
createGame()
This is index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Section 5: Advanced JavaScript: Objects and Functions</title>
</head>
<body>
<h1>Section 5: Advanced JavaScript: Objects and Functions</h1>
<script src="script.js"></script>
</body>
</html
My goal with this simple program was to keep outputting a question until the user got it right. If the user got the question right, you would console.log("You won!") and the program would stop running. I did this with the help of ternary operators. However, why does my program keep running forever?
checkAnswerALWAYS returns undefined because you aren'treturn-ing anything: