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

200
Views
I want to console.log a random array it works when I pass in a number but it doesn't when I directly hard code it in the console.log()

When I do this, the code works.

console.log(characters.data.results[2])

I would obviously get the third object in the array. but this is static. I want it to be randomized so I did this.

console.log(Characters.data.results[Math.floor(Math.random() * 21)])

it didn't work, I keep getting this error

Main.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading 'results')
at Main (Main.jsx:6:1)
at renderWithHooks (react-dom.development.js:16175:1)

I even made the code cleaner by doing

const random = Math.floor(Math.random() * 21);
console.log(characters.data.results[random])

but I got the same error. What am I doing wrong? I am new to react.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The value of Characters.data is undefined on first render and maybe changing afterwards.

To make sure Characters.data is not undefined before accessing Characters.data.results. You can use optional chaining (?.)

console.log(Characters.data?.results[Math.floor(Math.random() * 21)])
about 4 years ago · Juan Pablo Isaza Report
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!