Summary: In this tutorial, you will learn the difference between let and var in JavaScript with the help of the examples.
In JavaScript, var
and let
are both used for declaring variables, but they have some differences in the way they behave.
1. Scope
The main difference between var
and let
is the scope in which they are declared. var
variables are function-scoped, which means that they are defined throughout the entire function in which they are declared, and are accessible anywhere within that function.
let
variables, on the other hand, are block-scoped, which means that they are defined within the block in which they are declared and are only accessible within that block.
Here is an example to illustrate the difference in scope between var
and let
:
if (true) {
let x = 'hello';
var y = 'world';
}
console.log(x); // ReferenceError: x is not defined
console.log(y); // "world"
In this example, the let
variable x
is defined within the block of the if
statement, and is only accessible within that block.
Therefore, trying to access x
outside of the block will result in a ReferenceError
. The var
variable y
, on the other hand, is defined throughout the entire function and is accessible anywhere within the function, so it can be accessed outside of the if
block.
2. Hoisting
var
variables are hoisted to the top of their scope, which means that they can be accessed and used before they are declared.
let
variables, on the other hand, are not hoisted, and trying to access them before they are declared will result in a ReferenceError
.
console.log(x); // undefined
var x = 'hello';
console.log(y); // ReferenceError: y is not defined
let y = 'world';
3. Re-declaration
var
variables can be re-declared within the same scope, while let
variables cannot. If you try to re-declare a let
variable within the same scope, you will get a SyntaxError
.
var x = 'hello';
var x = 'world'; // this is allowed
let y = 'hello';
let y = 'world'; // SyntaxError: Identifier 'y' has already been declared
4. Temporal Dead Zone
let
variables have something called the “Temporal Dead Zone” (TDZ), which is the period of time between the variable’s declaration and its initialization.
During this time, trying to access the variable will result in a ReferenceError
. var
variables do not have a TDZ.
console.log(x); // ReferenceError: x is not defined
let x = 'hello';
console.log(y); // undefined
var y;
I hope these examples help to illustrate some of the differences between var
and let
in JavaScript