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. – jhominal Apr 09 '15 at 13:19function foo() {...}
is better than<anything> foo = function() {...}
– OrangeDog Apr 09 '15 at 14:48function 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
. – Keen Apr 09 '15 at 19:27Natural order of function declaration is highly subjective. It might be reasonable to think that the natural order is to start by defining the basic pieces, and then later define the pieces that use them.
– Keen Apr 09 '15 at 19:38const
andlet
here. – thefourtheye Apr 10 '15 at 15:34let
... freezing the reference in memory, or some other expensive checks. I useconst
in anonymous/throw-away callback functions, and didn't want to laden repetitive, low-value functions with expensive ops. I don't think that's the case. – Lee Benson Oct 16 '15 at 18:53