Please, always use const
June 05, 2016
Say hello to new friends let & const
ES6 among other very useful features, introduced block-scoped delcarations. A block is basically a piece of code delimited by a pair of curly brackets, so function
body is a block and also if
, while
, switch
statements. Once you understand how const
and let
work, you can use them to improve readability and performance of your code. The first one: let
is a safer replacement for var
, the difference is that var
is function
scoped.
This example from MDN shows the the diffrence between var
and let
:
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
Const
is an immutable reference. If you assign a primitive type(Boolean, Null, Undefined, Number, String, Symbol) value to a const
is behaves like a real constant. JavaScript object is a reference type, so even if you assign an object to a const
variable you can still change it’s properties, you just can’t change the assignment.
const clients = [];
clients.push('John Smith'); // no error
clients.push('Michael Brown'); // no error
clients = []; // Error
A recommended practice:
Always use const
- change to let
only when a IDE or Linter complains about it. As a result about 95% of your declarations should be const
. In many compiled languages the compiler will use constants to optimize code by removing dead
- unreachable blocks. The good news is that the JavaScript runtime Node.js uses the V8, compiles JavaScript to machine code using JIT - just in time compiler. Soon new versions of JIT will optimize the usage of const
. So by applying to the always const rule you are gaining performance in the future for free. Another benefit is that it increases the readability of your code, it’s easier to reason about references that do not change. If you see a let
declaration you will expect a reassignment somewhere inside the same block.