Handling common JavaScript problems - bad for loop

In the Handling common JavaScript problems article it’s written that in bad-for-loop.html, i is reported to be 11 when the paragraph is clicked.

      for(let i = 1; i <= 10; i++) {
        const para = document.createElement('p');
        para.textContent = 'This is paragraph ' + i + '.';
        para.onclick = function() {
          alert('Hello from paragraph ' + i + '!');

I tried it on 3 modern browsers (Firefox, Chrome and Edge) and i is reported to be the correct number of the paragraph and not 11.
On Internet Explorer it’s indeed reported to be 11.

Any explanation will be appreciated.

Hello @Rafael_Green

that good one
but not sure my explanation is right or not
but i think it depend on how complicated is your nested function so if require huge process it could lead to that error

hope @chrisdavidmills help us here

and have a nice day both of you :slight_smile:

Hi @justsomeone,
Thank you for the answer but I think it is related to closures (no matter how complicated the function is)

you very welcome @Rafael_Green
could be also that

On Internet Explorer it’s indeed reported to be 11.

When is i inpected in the code?

let i = 1;
for(; i <= 10; i++) {
// 11 at Nightly 82, Chromium 87

sorry, but I didn’t understand your question

Where and when in the code is 11 printed?

your code would not make it print 11 as it not nested function

and @Rafael_Green say it work fine except with IE

hope that help and have a nice day

The question is when and where in the code 11 is printed. i is post-incremented. If i is looged after the for loop the value of i will be 11.

11 is printed in the last line of the code at the end of the execution of the code

If understand you correctly is the output

This is paragraph 1.

This is paragraph 2.

This is paragraph 3.

This is paragraph 4.

This is paragraph 5.

This is paragraph 6.

This is paragraph 7.

This is paragraph 8.

This is paragraph 9.

This is paragraph 10.

This is paragraph 11.



Am not sure what to state here. Have not used IE in well over a decade. MS stated support for IE will be dropped in 2021https://techcommunity.microsoft.com/t5/microsoft-365-blog/microsoft-365-apps-say-farewell-to-internet-explorer-11-and/ba-p/1591666.

Why is IE being tested at all?

The for loop is not the issue, IE is the issue.

Does IE even support let?

IE is being tested because there are still people who use it

there is a partial support on IE 11

see https://caniuse.com/let

It is not clear what

5 let variables are not bound separately to each iteration of for loops


Though, again, with modern FOSS browsers available, why is use of IE necessary, here?

I didn’t understand it either

what is FOSS?