I was interviewed for a JavaScript frontend developer position. I failed because I didn't know a few advanced questions. Please help me to understand at least this one.
My problem was on ECMAScript 6 knowledge, not the for loop in ECMAScript 5 or the closure. I didn't understand what is doing for/of
or who is doing the magic in this ECMAScript 6 code to not overwrite the i
.
The question was like:
To display numbers from 1 to 5 in the for loop, every time we click on a button, we have to wrap the console in a closure, to have the right output, so the
i
variable will not be overwritten if we use this closure.In ECMAScript 6, in a
for
loop we only have the callback function, andi
is not overwritten. Why?// ECMAScript 5 for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(x) { return function() { console.log(x); }; }(i) ); document.body.appendChild(btn); } // ECMAScript 6 const ps = Array.from(document.querySelectorAll('p')); for (const [i, paragraph] of ps.entries()) { paragraph.addEventListener('click', function() { return console.log(`${i+1}: ${this.textContent}`); }); }