1

This is my first time writing code that actually needs to run properly on IE11 and it's not very fun.. Can anyone ascertain why i is incremented on line 6 in the below Javascript code?? Both Chrome and IE are given the same upper bound in the for loop, yet somehow the code run on explorer surpasses that upper bound? Any advice would be greatly appreciated.

console.log("headers length:", headers.length);
for (let i = 0, max=headers.length; i < max; i ++) {
    console.log("i:",i);
    let item = headers[i];
    item.addEventListener("click", function(event){
        console.log("column before func call:", i);
        current_sort_column = sort_by(table, i, current_sort_column);
    });
}

When run on Google Chrome:

headers length: 8
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
column before func call: 2

When run on IE:

headers length: 8
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
column before func call: 8
Hannah Smith
  • 103
  • 1
  • 5
  • 7
    IE doesn't block scope `let`. Only Edge does – Taplar Dec 27 '19 at 19:12
  • 1
    @Taplar actually, IE does know what `let` is, it just doesn't create the scope correctly click the down arrow in the support grid on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – Heretic Monkey Dec 27 '19 at 19:15
  • i is still incremented before it's tested (that's how i gets to 8); it's not being properly captured in the function (@HereticMonkey's link explains why). – brnlmrry Dec 27 '19 at 19:15
  • 1
    Duplicate doesn't cover the `let` issue, but it does cover your *real* issue – Taplar Dec 27 '19 at 19:15
  • 1
    @HereticMonkey my bad, correcting. Which makes sense. If it didn't entirely know what it was, it'd be a syntax error all together – Taplar Dec 27 '19 at 19:15
  • See: https://caniuse.com/#feat=let –  Dec 27 '19 at 19:15
  • Note [Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the \[scope semantics\] wrong](https://stackoverflow.com/a/750506/1541563) – Patrick Roberts Dec 27 '19 at 19:18

0 Answers0