Why let at function scope in JavaScript?

2019-07-09 07:19发布

I understand the block vs. function scoping of let & var (or I thought I did). Recently I ran across some JavaScript that used let in function scope where I thought it would be equivalent to using var, like:

function xyz ( abc ) {
    let mno = abc - 1;   /* or whatever */
    ...
}

Is there any functional difference between that and using var there? Or is it just a stylistic thing?

3条回答
forever°为你锁心
2楼-- · 2019-07-09 07:33

No difference whatsoever. It's either a stylistic thing or a misunderstanding of how var and let work. Perhaps the original author (the person who wrote the function you saw) thought that let is the same as const (which is almost the case in languages like Swift). In other words, sometimes people bring styles/syntax from one language into another because the declarations look similar, but in reality mean completely different things.

I understand the block vs. function scoping of let & var (or I thought I did)

Don't worry, you do. let is for block-scoping, just as you pointed out.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-09 07:33

According to this answer, there is no difference in the case you described, they're functionally the same as they're both in the scope of the function. As you guessed, probably just the person (or linter) wanting to be consistent in defining variables.

查看更多
老娘就宠你
4楼-- · 2019-07-09 07:39

One difference inside function scope would be that temporal dead zone can occur if you try to reference a let before it's defined:

function example() {
    console.log(a); // undefined
    console.log(b); // ReferenceError: b is not defined
    var a = 1;
    let b = 2;
}
查看更多
登录 后发表回答