-1

The MDN tutorial for JavaScript says

Back when JavaScript was first created, there was only var. This works basically fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying. So, let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.

It continues to say

For these reasons and more, we recommend that you use let as much as possible in your code, rather than var. There is no reason to use var, unless you need to support old versions of Internet Explorer with your code (it doesn't support let until version 11; the modern Windows Edge browser supports let just fine).

I'm looking at JavaScript code in templates and tutorials and, almost universally, I see var for initializing variables.

Are the differences over-stated between var and let?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Sebastian
  • 957
  • 3
  • 15
  • 27
  • 1
    No, the differences are absolutely not over-stated. `let` is somewhat new, so any tutorial from before around 2015 would have used `var`. – Pointy Jan 31 '19 at 20:11
  • And for universal capability, many tutorials continue to use `var` because inertia. Any recent tutorial should at *least* be using `let`, preferably `const` when appropriate--but when the tutorial is about XYZ focusing on `var` vs. `let` vs. `const` often gets lost in the shuffle. – Dave Newton Jan 31 '19 at 20:25
  • Do you encourage beginners to stick with `let`? I am finding `var` useful when I enter JS commands that redefine a variable that may or may not have already been created. – Sebastian Jan 31 '19 at 20:33
  • You *shouldn't* really have a definition of a variable that might or might not be defined already. That's defeating the purpose of defining a variable in the first place. With that you may as well be using globals. So, yes `let` is encouraged if at least to get you to structure your declarations properly. In real-world code `var` has pretty much no advantage outside some really odd cases where you can probably just re-structure your code anyway. – VLAZ Jan 31 '19 at 20:54

1 Answers1

0

Var has a larger scope then let let is only valid in the block where it was declared . Try adding 10 clickhandlers that output a numbers in a loop and you will quickly see the difference