Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #31437
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: Confused about let and var |
| Date | 2016-09-23 19:26 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <87intmh3pr.fsf@bsb.me.uk> (permalink) |
| References | <57e4e5d9$0$876$e4fe514c@news.xs4all.nl> |
Erwin Moller <erwinmollerusenet@xs4all.nl> 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);
> }
<snip>
> 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.
Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Confused about let and var Erwin Moller <erwinmollerusenet@xs4all.nl> - 2016-09-23 10:20 +0200 Re: Confused about let and var Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-09-23 19:26 +0100 Re: Confused about let and var Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-09-24 18:12 +0200
csiph-web