So far we have used the var
keyword to declare variables.
When JavaScript was first created in 1995, this was the only way to declare a variable.
In 2015 JavaScript received a long overdue update that added many improvements.
This update gave us two new keywords for declaring a variable: let
and const
Let it Change
The keyword let
is almost identical to var
:
let x;
x = 5;
console.log(x);
let y = x + 2;
console.log(y);
Key Differences
There are a few differences between let
and var
, which we will break down:
var
is function scoped andlet
is block scopedvar
variables can be used before the line where they are declared
var and let are scoped differently
Using var
creates a variable that can be accessed from anywhere in the function:
function varDemo() {
var x = 2;
console.log(x); // 2
{
var x;
console.log(x); // 2
x = 5;
console.log(x); // 5
x += 3;
console.log(x); // 8
}
console.log(x); // 8
}
varDemo();
See how the same x variable is used throughout the function, even inside the code block?
When we try to re-declare x, we really just get the same x variable as before.
Using let
will actually create a new variable with its own value:
function letDemo() {
let x = 2;
console.log(x); // 2
{
let x;
console.log(x); // undefined
x = 5;
console.log(x); // 5
x += 3;
console.log(x); // 8
}
console.log(x); // 2
}
letDemo();
The variable x inside the block is a completely different variable from the one declared outside the block.
This means we can be certain that the let
variable we are working with isn't interacting with other code outside the block.
Always use let
instead of var
.
var works from anywhere
This means that a variable declared with var
can be used anywhere in the same function, but a variable declared with let
can only be used in the same block.
For example:
function addFive(x) {
console.log(result);
var result = x + 5;
console.log(result);
return result;
}
addFive(12);
See how var
allows us to access the variable result
before we actually declared it? Its value is undefined
because we haven't assigned it a value, but we can access it without throwing an error.
Using let
would throw an error because the variable doesn't exist yet:
function addFive(x) {
console.log(result);
let result = x + 5;
console.log(result);
return result;
}
addFive(12);
This means we have to declare our variables before we use them if we use let
. That's a good thing! It makes code more organized.
Always use let
instead of var
.