views:

4914

answers:

3

In javascript 1.7, the let keyword was added. I've heard it described as a "local" variable, but I'm still not quite sure how it behaves differently than the var keyword.

What are the differences between the two? When should let be used over var?

+3  A: 

Right now you should almost never use let, because you usually can't count on it being fully supported yet in the wild.

I know that's not the kind of answer you were looking for, but it's probably the most important consideration. If you have a limited deployment where you know everyone gets 1.7, then you're a lucky fellow.

Joel Coehoorn
I already knew I couldn't use it due to IE6 support, but I'd like to know what it does exactly.
TM
+11  A: 

Here's an explanation of the let keyword with some examples.

This table on Wikipedia shows which browsers support Javascript 1.7.

Note that IE does not support it.

Ben S
The key bit of text from the linked document seems to be, "let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function".
Michael Burr
While it's technically correct to say IE does not support it, it's more correct to say that it's a mozilla only extension.
olliej
+4  A: 

There are some subtle differences -- Let scoping behaves more like variable scoping does in more or less any other language -- eg. it scopes to the enclosing block, they don't exist before they're declared, etc

However it's worth noting that let is also a Mozilla extension, not part of any standard (EcmaScript is the standard, JavaScript is the mozilla implementation, the history is slightly convoluted but that's how it goes), and so let is only available in firefox and other mozilla based browsers.

olliej