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
268 views
in Technique[技术] by (71.8m points)

'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?

Since according to What's the difference between using "let" and "var" to declare a variable?, the let keyword has a smaller scope than var when used in a for loop. Does this mean that of all the places where 'for (var i=0...' the actual correct way should be to use let? I can't imagine a case where a developer who was using 'for (var i=0...' would want to have the var i still be visible outside the for loop, meaning that all 'for (var i=0...' are wrong and the correct way is 'for (let i=0...'? Just a yes or no question.

function allyIlliterate() {
    //tuce is *not* visible out here

    for( let tuce = 0; tuce < 5; tuce++ ) {
        //tuce is only visible in here (and in the for() parentheses)
    };

    //tuce is *not* visible out here
};

function byE40() {
    //nish *is* visible out here

    for( var nish = 0; nish < 5; nish++ ) {
        //nish is visible to the whole function
    };

    //nish *is* visible out here
};
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

let is introduced in Ecma Script 6 - the new javascript version - which is still in development at the time of this writing. Therefore, using var will get you across more browsers for the time being.

On the other hand, I urge people to use let instead of var from now on. I would go ahead and list the reasons but you have already have a link in your post with a great explanation in it. Long story short, let helps you avoid the variable hoisting in javascript and keep your variables' scope at just where it needs to be.

update

I've forgotten about this post until I recently got an upvote. I'd like to update this statement. I personally use const as much as I can these days. If you get into linting your code, which I highly recommend, and use something like airbnb lint rules, it will also tell you to use const. It will make your variables a constant so you will not be able to mutate them once you set their value thus it is not applicable in all cases. const and let also have advantages in terms of scope over var and it is well worth a read. My hierarchy of usage goes as such const > let > var


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

...