Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Apparently the only difference is that var gets scoped to the current function,

ID: 648235 • Letter: A

Question

Apparently the only difference is that var gets scoped to the current function, while let gets scoped to the current block. There are some good examples in this answer.

I can't see any reason to use var in ES6 code. Even if you want to scope a given variable to the whole function, you can do so with let by putting the declaration at the top of the function block, which is what you should be doing with var anyway to indicate the actual scope. And if you want to scope something more finely in an for block or something, then you can do that too.

So my instinct is to stop using var altogether when writing ES6 code.

My question is, am I wrong about this? Is there any legitimate case where var would be preferable over let?

Explanation / Answer

Doug Crockford discusses let at this point in his recent talk, "The Better Parts".

Essentially, let avoids a source of misunderstanding, esp. for programmers with expectations set by languages with block-scope. A var has function scope (it declares a variable that's visible throughout the function) even though it looks like it has block scope.

var might possibly still be useful in some kind of extreme case like machine-generated code, but I'm really stretching hard there.

Realistically, your impression is right on for ES6: Adopt let and stop using var.

(BTW, it's totally worth watching Doug's entire talk. He gives the same answer for using === instead of ==. The latter is broken but the ES standards committee didn't want to change it, so they added ===.)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote