Why is there a "let" statement in JavaScript 1.7?
I was looking at the JavaScript 1.7 specification recently and it wasn't immediately obvious to me what the purpose of the new let statement was for. I'll give you a hint: it's related to closures.
I am not by any means a JavaScript expert. I've only done some small JavaScript hacking over the years (including a little Cat interpreter online). I almost like the language. Recently though I was wondering though what special purpose the "let" statement in JavaScript 1.7 served.
The documentation at http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 wasn't immediately obvious to me on a superficial reading. Here is what the documentation said:
let statements, expressions and definitions sometimes make the code cleaner when inner functions are used.
var list = document.getElementById("list"); <br />for (var i = 1; i <= 5; i++) { <br /> var item = document.createElement("LI"); <br /> item.appendChild(document.createTextNode("Item " + i)); <br /> let j = i; <br /> item.onclick = function (ev) { <br /> alert("Item " + j + " is clicked."); <br /> }; <br /> list.appendChild(item); <br />}The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of variable j. Note that it does not work as intended if you replace let by var or if you remove the variable j and simply use the variable i in the inner function.
Once you do the suggested mental exercise it should become obvious that when you replace "j" with "i" in the onclick function, every element in the list will trigger an alert with the text "Item 5 is clicked" when clicked. This is because each function would be bound to the same "i" variable, which eventually gets assigned the value 5.
It shouldn't take too much for an intermediate to advanced programmer to understand the problem that the introduction of the "let" statement solves, I am not so sure that adding it as a langauge feature is a good idea. It really hurts the simplicity and elegance of the language (and thus its appeal to beginners), just to provide some modern conveniences to advanced users.
The general problem with adding language features to make certain programming problems have simpler solutions, is that it isn't obvious to newcomers what problems a given language feature is in fact solving.

