2

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?

2

3 Answers 3

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@max Not sure, but I remember reading a while back that he was basically rushed by Netscape to come back to them in 10 days with a new language prototype (hence all the strange js bugs that carry through to today)
3

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 Comments

Thanks, I was burned by perl's ridiculous my scoping once, so I wanted to make sure there wasn't some silly corner case I was unaware of.
No problem. No weird corner cases here, as far as I'm aware.
Except that var hoists while let works well - in a less silly and confusing manner. Many have advocated that you should replace var everywhere because its just less confusing for programmers from other languages.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.