Difference Between let and var in JavaScript
In this tutorial, we'll discover the difference between using the let
and var
variable declaration keywords in JavaScript.
The Difference
Both keywords declare variables in JavaScript. The difference lies in the scope of those defined variables:
- Variables declared using the
let
keyword are only available within the code block in which they're defined. - Variables declared using the
var
keyword are available throughout the entire code block or function in which they're defined. Similarly, if these keywords get declared at the top of a script, they can be utilized throughout all code blocks and functions of that script.
Examples
Let's look at some code examples for each keyword.
function myFunc() {
let num = 1;
if (true) {
let num = 2;
console.log(num);
}
console.log(num);
}
As you can see, the variable num
gets defined with a value of 1 at the top of the function, then changed to 2 inside a conditional block. The first console output shows 2 as the value because it's inside the conditional block, but outputs 1 once outside the code block. This is because the let
keyword only works for variables within the same block.
Now, using the var
keyword, you'll see that both console outputs show 2 as the output. That's because this type of keyword declaration is available to the entire function rather than just the individual child blocks:
function myFunc() {
var num = 1;
if (true) {
var num = 2;
console.log(num);
}
console.log(num);
}
Global Declarations
In one final example, let's see what happens when we create a global declaration of our num
variable:
var num = 1;
function myFunc() {
if (true) {
let num = 2;
console.log(num);
}
console.log(num);
}
myFunc();
The num
variable now gets declared at the top of our script with a value of 1. The call to myFunc()
is made, and num
gets set to 2 inside of a conditional block. This will output 2 inside that block, but still output 1 outside the block. This is because the let
keyword declaration only exists within that single code block. The num
variable can be used anywhere throughout this script and contain a value of 1 unless otherwise changed globally with var
.
Conclusion
That covers the differences between let
and var
variable declarations in JavaScript.