Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
TypeError when Using API in Javascript

I'm trying to make a Trivia Game using Open Trivia DB.
What I want is to display only the questions in the triviaQ constant and I did that. The code works, it does what I want it to do BUT, when I refresh the page sometimes, this error shows up in the console:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'question')
The error points to: question_data.question and underlines the question which doesn't make sense because it is a valid key from the API json. Plus, what confuses me even more is that it still displays the question even if there is an error and the error appears sometimes. Thank you in advance for your time!

Javascript Code:

const api_url = 'https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean'
const triviaQ = document.getElementById("triviaQuestion")
let question_data = ""

async function display() {
    const response = await fetch(api_url);
    const data = await response.json()
    for (let i = 0; i <= 10; i++) {
        var randNum = Math.floor(Math.random() * 11);
        question_data = data.results[randNum]
        triviaQ.innerHTML = question_data.question
    }
}

display()
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!