Understanding var, const, and let in JavaScript: A Comprehensive Guide with Examples
In JavaScript, there are three ways to declare variables: var
, let
, and const
. Each of them has slightly different behavior and scoping rules. Here are some examples:
var
: Declaring a variable usingvar
has function scope. It is hoisted to the top of its scope, which means you can access it before its actual declaration.
function example() {
var x = 10;
if (true) {
var x = 20; // This will overwrite the outer x
console.log(x); // Output: 20
}
console.log(x); // Output: 20
}
example();
2. let
: Declaring a variable using let
has block scope. It is not hoisted and is limited to the block where it is defined. This allows you to have variables with the same name in different blocks without conflicts.
function example() {
let x = 10;
if (true) {
let x = 20; // This creates a new x variable within the block
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
example();
3. const
: Declaring a variable using const
also has block scope, similar to let
. However, const
variables are constants and cannot be reassigned after they are initialized. They must be assigned a value when declared.
function example() {
const x = 10;
if (true) {
const x = 20; // This creates a new x constant within the block
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
example();
function example() {
const x = 10;
x = 20; // This will throw an error as x is a constant
}
example(); // Output: TypeError: Assignment to constant variable.
Note that variables declared with var
and let
can be reassigned, but var
variables have function scope, while let
variables have block scope. const
variables, on the other hand, cannot be reassigned and also have block scope.