Why let at function scope in JavaScript?

2019-07-09 07:29发布

问题:

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?

回答1:

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.



回答2:

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;
}


回答3:

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.