I've been writing a lot of ES6 code for io.js recently. There isn't much code in the wild to learn from, so I feel like I'm defining my own conventions as I go.
My question is about when to use const
vs let
.
I've been applying this rule: If possible, use const
. Only use let
if you know its value needs to change. (You can always go back and change a const
to a let
if it later turns out you need to change its value.)
The main reason for this rule is it's easy to apply consistently. There are no grey areas.
The thing is, when I apply this rule, in practice 95% of my declarations are const
. And this looks weird to me. I'm only using let
for things like i
in a for
loop, or occasionally for things like accumulated Fibonacci totals (which doesn't come up much in real life). I was surprised by this – it turns out 95% of the 'variables' in my ES5 code to date were for values that do not vary. But seeing const
all over my code feels wrong somehow.
So my question is: is it OK to be using const
this much? Should I really be doing things like const foo = function () {...};
?
Or should I reserve const
for those kind of situations where you're hard-coding a literal at the top of a module – the kind you do in full caps, like const MARGIN_WIDTH = 410;
?
const
this much.function foo() {...}
is better than<anything> foo = function() {...}
function foo() {...}
can cause minor confusion when debugging, due to hoisting. Also, its existence means that we have two constructs that do the same thing but one of them only works in a very specific context. (You can using a function expression anywhere an expression can exist, but you can only use a function declaration at the statement level.) If you favor brevity, the problem might just be that the function expression syntax uses the whole wordfunction
.