Skip to content
Advertisement

How do I get the index of two variables, compare them, and return true or false

I am making a trivia game that uses an array of objects.

JavaScript

I think the correct way is to get the index of the correct answer by using .find, getting the the index of the selected answer, then use an if statement to compare the two. If they match then the console will log “correct” or “incorrect” otherwise. I am having trouble getting the index of corretAnswer and also selectedAnswer.

When I use this code and console log it, both variables return undefined.

const answerButtons = document.querySelectorAll('.answers-btn');

JavaScript
JavaScript

Advertisement

Answer

I tried to create a solution with as least code possible. First, you don’t need to add an event listener to each button, you could just make each call a specific index from HTML. Secondly, since you are creating your answers list with a correct property, you don’t need to iterate it. Just get the one the user selected and check the property.

Hope it helps.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement