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

315
Visualizações
The Logic of forEach() when works with variables in javascript?

the result of code is :

test0: apple
1: orange
2: cherry

I want to know why my text variable is equal to "" in second and third loop, I expected the previous values to be added to the initial value of the text variable, Can anyone explain what happens to the text variable and what is the logic of forEach in this example ?

let text = "test";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text += index + ": " + item + "<br>";
}
<p id="demo"></p>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your loop runs such that the text test is only added once. In the beginning and then later the variable text is updated.

If you want to add in every iteration just keep it in a seperate variable and keep adding.

let text = "";
let test = "test";

const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {
  text = text + test + index + ": " + item + "<br>";
}
<p id="demo"></p>

about 4 years ago · Juan Pablo Isaza Relatório

0

Your codes works as expected. using innerText rather than innerHTML might illuminate the situaion

let text = "test";
const fruits = ["apple", "orange", "cherry"];
//fruits.forEach(myFunction);

document.getElementById("demo").innerText = text;

function myFunction(item, index) {
  text += index + ": " + item + "<br>";
  document.getElementById("demo").innerText = text;
  console.log(item,index);
}

window.setTimeout( myFunction.bind(null,fruits.shift(),0), 1000);
window.setTimeout( myFunction.bind(null,fruits.shift(),1), 2000);
window.setTimeout( myFunction.bind(null,fruits.shift(),2), 3000);
<p id="demo"></p>

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