Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda