JavaScript: var vs const vs let
In JavaScript, what's the difference between var
, const
and let
? In previous generations of JavaScript, only var
was available. The latter two were added as part of ES2015.
Scope
Both let
and const
are blocked scoped variables whereas var
was not blocked scoped. All var
declared variables are "hoisted" effectively making each variable equivalent in scope regardless of where it was declared. As an example consider this:
for (let i = 0; i < a.length; i++) {
let x = a[i]
…
}
for (let i = 0; i < b.length; i++) {
let y = b[i]
…
}
let callbacks = []
for (let i = 0; i <= 2; i++) {
callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4
// -----------------------
var i, x, y;
for (i = 0; i < a.length; i++) {
x = a[i];
…
}
for (i = 0; i < b.length; i++) {
y = b[i];
…
}
var callbacks = [];
for (var i = 0; i <= 2; i++) {
(function (i) {
callbacks[i] = function() { return i * 2; };
})(i);
}
callbacks[0]() === 0;
callbacks[1]() === 2;
callbacks[2]() === 4;
const
means that an identifier cannot be reassigned. It's not quite immutable as the value can still be changed but not reassigned. The difference is the following.
const a = {a:1};
a.a = 2; //Valid; we're changing the object represented by a
a = {b:2}; //invalid as we're replacing the object
Best Practice
In my opinion, best practice is to use const
and let
when where possible. Generally, it's not possible to use in code intended for use in a web browser were broad browser support is required.
It is possible in things like Node.JS and if you are using babel or web-pack (and related). These latter tools convert the code to browser capable.