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

311
Views
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 answers
Answer question

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 Report

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 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!