0

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>
lejlun
  • 4,140
  • 2
  • 15
  • 31
  • 4
    Your code is working exactly as it should. If you want "test0" at the beginning of every line, you'll have to append it *inside* the loop. – Pointy Oct 29 '21 at 21:14
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Oct 29 '21 at 21:17

2 Answers2

1

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>
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
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>
code_monk
  • 9,451
  • 2
  • 42
  • 41