-
It's not possible to access the let
variable outside of the nearest enclosing block where it is declared.
{
let foo;
}
console.log(foo);
The sample code above works if we replace the let
with var
declaration.
-
A let
variable can't be used before it's declared. The sample code below throws a ReferenceError
:
{
foo = 'hello';
let foo;
console.log(foo);
}
We will see hello
in the Console if we use var
in the sample code above.
-
It's not possible to re-declare variables with let
.
var foo, foo;
var bar;
var bar;
let baz;
let baz;
-
At the top level, global let
variables aren't attached to the global window
object.
let foo = 'hello';
window.foo;
var bar = 'world';
window.bar;
-
Using let
can avoid the problem with closures that var
has.
To demonstrate the problem, let's assume that we have a list of rows. In each row, we have a button for removing the associate item in the row.
We loop over the items, and handle the click
event of the button in each row:
for (var i = 0; i < 10; i++) {
document.getElementById(`button-\${i}`).addEventListener('click', function () {
console.log(i);
});
}
It doesn't work as we expect. We always see the last item index (9
in this case) in the Console when clicking any button.
The variable i
in the closure of event handler will refer to the same object, which is the last index when looping over the indexes.
The problem can be fixed by using let
:
for (let i = 0; i < 10; i++) {
document.getElementById(`button-\${i}`).addEventListener('click', function () {
console.log(i);
});
}
-
The const
keyword behaves same as let
, except the variable can't be changed.
You also have to specific a value for a constant.
const a = 'hello';
a = 'world';
It's worth noting that using const
doesn't mean that the variable is immutable. You can change the properties of an object:
const person = {};
person.age = 20;
And add more items to an array:
const arr = [];
arr.push('foo');
arr[1] = 'bar';
console.log(arr);
Each programming language use different keywords to declare a variable and constant.
The following table list out some examples: