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

141
Views
Iterating through an arrays with a for loop in Javascript only returns first value?

This loop only returns the first index of the array and stops there.

const numArr = [2,4,6,8,10];

const iterate = (array) => {
    for (let i = 0; i < array.length; i++) {
        return array[i]
    }
};

console.log(iterate(numArr));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Using return will end the loop in the first iteration

try

const numArr = [2,4,6,8,10];

const iterate = (array) => {
    for (let i = 0; i < array.length; i++) {
        console.log(array[i])
    }
};

iterate(numArr);

about 4 years ago · Juan Pablo Isaza Report

0

As Take-Some-Bytes mentioned in his comment it is because of the return statement. In JavaScript functions will stop executing when a return statement is called.

In your case, you call the function, the function starts looping through the array, it starts at the first item, sees a return statement and stops execution of the function.

On another note: This iterate method seems a little boiler plate or re-inventing things that are already available.

For example, have you tried:

const numArr = [2,4,6,8,10];
numArr.forEach(item => {
  console.log(item)
})

The code above does the same thing as:

const numArr = [2,4,6,8,10];

const iterate = (array) => {
    for (let i = 0; i < array.length; i++) {
        console.log(array[i])
    }
};

iterate(numArr);
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!