Closing (let keyword) - Javascript

function first(){
    var items = document.getElementsByTagName("li");

    for(var x = 0; x < items.length; x++){
        items[x].onclick = function() {
            console.log(x);
        }
    }
}

function second(){
    var items = document.getElementsByTagName("li");

    for(var x = 0; x < items.length; x++){
        (function(val) {
            items[val].onclick = function() {
                console.log(val);
            }
        })(x);
    }
}

function third(){
    var items = document.getElementsByTagName("li");

    for(let x = 0; x < items.length; x++){
        items[x].onclick = function() {
            console.log(x);
        }
    }
}

There are 4 items in the list. The outputs of three functions:

first: 4 4 4 4
second: 0 1 2 3
third: 0 1 2 3

I can not understand the output of the third function. In the second function, each IIFE call creates a new function object and, therefore, a new variable, val. But in the third function there is a single copy of the variable x, then how is the output: 0 1 2 3

Please correct me if I am wrong.

+4
source share
3 answers

In the documentation for let from MDN, they have an example covering this exact case in the cleaner code in internal functions :

for (let i = 1; i <= 5; i++) {
  let item = document.createElement('li');
  item.appendChild(document.createTextNode('Item ' + i));

  item.onclick = function(ev) {
    console.log('Item ' + i + ' is clicked.');
  };
  list.appendChild(item);
}

, , () i. , , let var, i: 6. , , .

, let, x. . , let , , var.

+3

let.

, let (& for-loop), , . , , 4 ( [0] [3]), .

for-loop third function :

items[0].onclick = function() {
        console.log(0);
   }
items[1].onclick = function() {
        console.log(1);
   }
items[2].onclick = function() {
        console.log(2);
   }
items[3].onclick = function() {
        console.log(3);
   }

let , MDN. .

+1

: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

let allows you to declare variables that are limited in scope by the block, statement or expression on which it is used. This is not like the var keyword, which defines a variable globally or locally for an entire function, regardless of block area.

When it is var, it rises, like all variables.

When allowed, scope is the block in which it is defined.

0
source

Source: https://habr.com/ru/post/1671249/


All Articles