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

145
Views
For loop only returns last number

I have made a for loop in order to console log multiple entries in an array. The for loop, however, only returns the last entry in the array, instead of everything from 0 to end of array.

for (var i = 0; i < roa.length; i++) {questionContentRoa = roa[i].questionContent, correctAnswerRoa = roa[i].correctAnswer }
                console.log(questionContentRoa, correctAnswerRoa);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It will be clearer to you if you ident the code a little bit.

The console.log is outside of the scope, hence, it's only logging the last assignment before the loop ends.

for (var i = 0; i < roa.length; i++) {
    questionContentRoa = roa[i].questionContent;
    correctAnswerRoa = roa[i].correctAnswer;
}
console.log(questionContentRoa, correctAnswerRoa);
about 4 years ago · Juan Pablo Isaza Report

0

The console.log should be inside the for loop. You have placed it outside.

Alternatively, an easier way to iterate through an array is by using the forEach loop.

roa.forEach((item)=>{
console.log(item.questionContent, item.correctAnswer );
}); 

// in the first iteration item would be the roa[0], 
//then in the second iteration it would be roa[1] and so on until the array ends..

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!