15

With the new keyword let for declaration of variables in javascript ES6, I can no longer think of good reasons to use var. So far, I have been doing just that and I do not see any disadvantage of using let ALL THE TIME.

What are good reasons to use var today? Is it a good practice to use let all the time today?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • 2
    This question has been answered [here](http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable) – txtechhelp Dec 08 '16 at 03:38
  • 1
    Thanks. I have read the question before (but not all of it). It is similar but it does not clearly make a stand on whether one should use `let` all the time. – guagay_wk Dec 08 '16 at 03:39
  • In short, Let vs var: Let - scoped to nearest closing block; not bound as a property to window object. Var - scoped to nearest function; bound to window object as a property. – clever_bassi Dec 08 '16 at 03:41
  • 1
    The answer gives a technical break down of `let` vs `var`, I would use `var` if it made sense, just like I would use `let` when it made sense (as in the second answer about closures), so there is not definitive answer to your question beyond the technicalities of it and what makes sense to you (e.g. an opinion). It's the same as asking if it makes sense to use `signed` vs. `int` in `C` (technically, they do the same thing, but it's about functionality and readability). – txtechhelp Dec 08 '16 at 03:42
  • Thanks for the comment. I guess so far, I have not encountered a case when var is more suitable. I have been using let all the time. THis is why I asked the question to see what I missed out. – guagay_wk Dec 08 '16 at 03:43
  • About the only thing I can think of as to what else might make sense, beyond scope, is address space/speed. If you're using `let` for all of your variables, you might not account for the memory and speed needed to address said variable by the browsers JavaScript engine. For smaller functions or scripts it might not matter at all (chances are that's the case for the majority). But for a massive site that makes heavy use of JS (or any server side JS), it might make an impact .. you'd have to do testing to verify that's the case for your stuff though .. – txtechhelp Dec 08 '16 at 03:51
  • The difference lies on the scope(`var` -> function scope, while `let` -> block scope). One obvious thing you are gonna lose if not using `var` is *variable hoisting*, which according to **Douglas Crockford** from Javascript should **never** be used. I will vote for `let` even though javascript is a FP language. – Allen Dec 08 '16 at 03:57

1 Answers1

9

IMO there is no definite advantage of using var over let, other than for its scope. One reason might be to support older browsers perhaps (if you don't plan to use an ES6 to ES5 compiler like Babel).

Divyanshu Maithani
  • 13,908
  • 2
  • 36
  • 47