Skip to content Skip to sidebar Skip to footer

Why Let At Function Scope In Javascript?

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

Solution 1:

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

functionexample() {
    console.log(a); // undefinedconsole.log(b); // ReferenceError: b is not definedvar a = 1;
    let b = 2;
}

Solution 2:

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.

Solution 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.

Post a Comment for "Why Let At Function Scope In Javascript?"