As io.js now supports ES6 you are finally able to use the const
and let
keywords. Obviously, let
is the successor of var
, just with some super-powers.
But what about const
? I know, of course, what "constant" means, but I was wondering when to use it (regarding best practices).
E.g., if I create a module that requires another module, I could write:
'use strict'; const util = require('util'); const foo = function () { // Do something with util }; module.exports = foo;
Basically I've replaced every occurence of var
with const
. Generally speaking, I think that this is okay, but if I follow this pattern, it leaves me with way more uses of const
than let
, as most variables aren't "variables" in a literal sense.
Is this good style? Should I rather go for let
? When should I choose const
over let
?
`const` is a signal that the identifier won't be reassigned. `let`, is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.
If I don't need to reassign, `const` is my default choice over `let` because I want the usage to be as clear as possible in the code. I use `let` when I need to reassign a variable. Because I use one variable to represent one thing, the use case for `let` tends to be for loops or mathematical algorithms.
The execution context underlying how the JavaScript interpreter runs the code is basically the same when you use var compared to when you use let and const . That results in the same execution speed.
The argument that prefers const when possible: One Way to Do It: It is mental overhead to have to choose between let and const every time. A rule like “always use const where it works” lets you stop thinking about it and can be enforced by a linter.
const
can be normally used when you don't want your program
to assign anything to the variable
"use strict"; const a = 1; a = 2;
will produce TypeError: Assignment to constant variable.
.
to use the variable without explicitly initializing.
"use strict"; const a;
will produce SyntaxError: Unexpected token ;
Simply put, I would say,
use const
whenever you want some variables not to be modified
use let
if you want the exact opposite of const
use var
, if you want to be compatible with ES5 implementations or if you want module/function level scope.
Use let
only when you need block level scoping, otherwise using let
or var
would not make any difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With