Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Confused about let and var Date: Fri, 23 Sep 2016 19:26:56 +0100 Organization: A noiseless patient Spider Lines: 71 Message-ID: <87intmh3pr.fsf@bsb.me.uk> References: <57e4e5d9$0$876$e4fe514c@news.xs4all.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="2680"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18a3p3sFw4/cAmT4t1GTzENXws6JD+MEuI=" Cancel-Lock: sha1:BK9606fdV18gI2SyEL9SVygb1CU= sha1:vnx8W8ZkjAvfK0hKr34uJQQDprU= X-BSB-Auth: 1.b29eece7ee299c01e2d1.20160923192656BST.87intmh3pr.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:31437 Erwin Moller writes: > On this page: > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let > > you can find the following example: > > ============================================================= > var list = document.getElementById("list"); > > 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); > } > This example of 'let' is confusing to me. > > Compare it to the following code: > > var list = document.getElementById("list"); > let i = 1; > while (i <= 5) { > 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++; > } > > In the above code 'let' behaves as 'var' and all clicks will result in > "Item 6 is clicked". > > (I am not sure I should use 'closure' in this context, but the code > behaves that way.) > > So what happens differently between these two codepieces? > 1) let i = 1; > while (i <= 5) {... > > > and > > 2) for (let i = 1; i <= 5; i++) {... > > Is the use of 'let' in the for-loop considered INSIDE the block? That's one way to look at it, yes. The actual rules are, as always with ECMA 262, very fussy indeed, but the 6th edition didn't just introduce 'let' declarations, it it also defined a whole new form of 'for' statement in which the first part in the ()s is a 'LexicalDeclaration'. The semantics of the new form make it plain that every loop execution occurs in a new environment with a fresh binding for the lexical variables. > (Because literally, it is not). Curiously, in C, a for statement constitutes a block which starts at the for keyword so there is a block even when there is no compound statement controlled by the for. ECMAScript does not do that, but the rules have the same effect. -- Ben.