Ad

Why Let At Function Scope In JavaScript?

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad