i read MDN pages about const, let, var. the summary of that is before ES2015 we have only global scope and function scope.in [this MDN page][1] there is an example of the benefits of block scope; that shows: instead of using closure concept to save related data for a function, like for loop iteration number, defined the loop variable as let. if the let keyword is only for block scoping how provide us this functionality? are other programming languages have this concept?
let divClassX = document.querySelectorAll('.x');
for (let j = 0; j < 2; j++) {
divClassX[j].onclick = function (event) {
console.log('class x div\'s x ' + j)
}
}
above code has the same functionality as :
let divClassX = document.querySelectorAll('.x');
for (var j = 0; j < 2; j++) {
divClassX[j].onclick = (function (j) {
return function (event) {
console.log('class x div\'s x ' + j)
}
})(j)
}
I assumed that some functionality like that exists so the blow code must work like above but when I clicked on div1 or div2 both times I get 2 but expected one when clicked on div 1 and two when I clicked on div2.
let div1 = document.querySelector('#div1');
let div2 = document.querySelector('#div2');
let i = 1;
div1.onclick = function (event) {
console.log(i);
}
i = i + 1;
div2.onclick = function (event) {
console.log(i);
}
what concept exists that I don't know? [1]: https://developer.mozilla.org/en-US/docs/Glossary/IIFE