What's the difference between let and var in JavaScript?
Both var
and let
are keywords that are used to declare variables in JavaScript (and TypeScript). The main difference between them is that variables declared with let
are block-scoped, while variables declared with var
are function-scoped
. This means that variables declared with let
are only accessible within the block they are defined in, while variables declared with var
are accessible everywhere within the entire function they are defined in.
var
Function Scope example
In the example below, the variable x
is declared with var
inside the function foo()
. It is accessible within the entire function, including within the block of the if
statement. However, it is not accessible outside of the function and we get ReferenceError: x is not defined
when we try to use it.
function foo() {
// Declaring a variable with var inside this function
var x = 10; // it will be available everywhere in this function
if (x > 5) {
// x is still accessible within the if block
console.log(x); // Output: 10
}
// x is still accessible within the function
console.log(x); // Output: 10
}
foo()
// x is not accessible outside of the function
console.log(x); // ERROR: Uncaught ReferenceError: x is not defined
let
Block scope example
function foo() {
// Declare a variable using let inside the function block
let x = 10;
if (x > 5) {
// Declare a variable with let inside the if block
let y = 20;
// Both x and y are accessible within the if block
// x is available because if is nested inside the function block
console.log(x); // Output: 10
console.log(y); // Output: 20
}
// x is still accessible within the function
console.log(x); // Output: 10
// y is not accessible within this block, because it was only defined within the if block
console.log(y); // ERROR Uncaught ReferenceError: y is not defined
}
// x and y are not accessible outside of the function
// Both the following statements will throw Errors
console.log(x); // ERROR Uncaught ReferenceError: x is not defined
console.log(y); // ERROR
var
and let
used outside of functions
If you use var
and let
in a script that doesn’t define any functions, both will be globally scoped for that script and available anywhere within it.
// Declaring a global variable with var
var x = 10;
console.log(x); // Output: 10
// Declare another global variable with let
let y = 20;
console.log(y); // Outputs: 20
// reassigning the global variables
x = 30;
y = 40;
console.log(x); // Output: 30
console.log(y); // Output: 40