ES6 question here. So my takeaway from learning about let
was "let
is better than var
, because hoisting. So stop writing var
today and never use it again." This sounds like less than the full picture to me. So if so, are there times to use var
and times to use let
?
Nope! var
really is on the way out. I would say that you should default to const
rather than let
and only use let
if the variable’s value will change at some point.
Example from a blogpost http://www.thinksincode.com/2016/10/16/its-ok-to-use-var.html:
I however do think it’s not ok to use var.
function foo(bar) {
console.log(baz); // undefined
if (bar) {
var baz = ‘Bar is truthy!’;
}
console.log(baz); // ‘Bar is truthy!’ (if bar is truthy)
}
The second console.log would be undefined too, when using let or const. Then again, I think it looks nicer to define the variable at the top of the function in stead of relying on var hoisting.
In my opinion you should be using let if you’re using ES6.
The main advantage is that let is scoped to its nearest enclosing block. Here is a stack overflow article thats pretty good.
I don’t think there is any reason to continue using var
over let
and const
except if you support older browsers that do not understand the new ES6 keywords. Even then, you can write ES6 code and transpile to ES5 using BABEL.
I agree with @PortableStick; default to const
and only use let
if you’re likely to reassign the variable at some point.
totally agree with @PortableStick to use const
as default, use var
if you think in some cases will be useful