We've learned about
let and const — what they do, and how they're scoped. We also know when they can be reassigned and when they cannot, but there's a question: What Should I actually use?
That's a bit of a hot topic in the community right now, because some people prefer to still use
var. Some people are saying, "var is dead!" Some say, "Use let." while others always use const.
var isn't dead - it still does what it always has done — it's function scoped and you can reassign or re-bind it. You may very well continue to choose it. There isn't a right answer here, just opinions. Check them out and make your own decisions.
Later on in the article he talks about
let vs. const...
letonly if rebinding is needed.
varshould not be ever used in ES6.
Whenever you make a variable, assume it's
const. Only use let if you need to update the value of the variable. You can use const to keep it the same value.
varfor top-level variables that are shared across many (especially larger) scopes.
letfor localized variables in smaller scopes.
let to constonly after some code has to be written, and you're reasonably sure that you've got a case where there shouldn't be variable reassignment.
He says, basically, Use
var to share larger scopes so you can put them inside of your function, and use let in smaller scopes. If you realize later that you need to update a value, you'd have to go back and make it a let instead of a const. If you use let, it's easier to go back and refactor them to const.
Both of those are very valid opinions. I'll let you make your own choice on that, but through the ES6.io series, I'll be using
const by default, let whenever I need to reassign a variable, and stay away from var entirely.
Find an issue with this post? Think you could clarify, update or add something?
All my posts are available to edit on Github. Any fix, little or small, is appreciated!