Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

> The above code is supposed to show a unique number for each button when the button is clicked. What it will actually do is to show the same number for all buttons, the number being equal to buttons.length.

no "let" will work as expected (lexical scoping). It's var which worked at the function scope, that's why "var" usage is not encouraged.

It's very confusing to JS newcomers, that's why it is important to learn the history of the language.



Actually it's not just lexical scoping.

If you had pure lexical scoping, given the way the for statement works, you would expect it to show the same value because it is the same x being captured.

JS actually specifically handles a for (let ...) specially by creating a _copy_ of the variable. See the spec[1] (the third clause starting with for (LexicalDeclaration ...)).

[1]: https://www.ecma-international.org/ecma-262/11.0/index.html#...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: