We’ve learned about
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
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.
This one, by Mathias Bynens, is how I do it. He says that “
const is not about immutability where you can change the properties.”
Later on in the article he talks about
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.
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
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