Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - let var or var to let

In the last couple of months, I've been learning a lot about JavaScript. Having abused the languages for years, I dare say that I now have a better understanding of the language and I've come to love the benefits of its functional nature.
Lately I've taken up learning Scheme, but that's just for fun. Browsing the MDN reference I noticed that JS, though lacking block scope, does have a keyword that can be used to declare a variable local to a given block, much like Scheme's let:

for (var i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//will log someArray's length

Whereas:

for (let i=0;i<someArray.length;i++)
{
    console.log(someArray[i]);
}
console.log(i);//undefined

So what I want to know now is: Why isn't let used more often? Has it got something to do with X-browser support? Is it just one of those lesser-known-goodies?
In short, what are the advantages of using var over let, what are the caveats?

As far as I can tell, the behaviour of let is, if anything, more consistent (double declarations in a single block raise a TypeError, except for function bodies (ECMA6 drafts fix this, though).
To be honest, apart from this feature/keyword not being very well known, I struggle to think of any argument against using let for loops, or anywhere where a temporary variable makes for more readable code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it has entirely to do with browser support. Currently only Firefox implements it (since it's part of their superset of ECMAScript).

But it is coming in ES6, so there's hope...

I doubt it could be said that there are many benefits to var over let given that both are supported. I think the mantra is going to be "let is the new var"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...