Javascript Tips: compare const and let and var statements
By JoeVu, at: Nov. 25, 2023, 6:33 p.m.
In JavaScript, let
, const
, and var
are used to declare variables, but they have some differences in terms of scope, hoisting, and mutability.
-
var
(Variable Declaration):- Variables declared with
var
are function-scoped, meaning their scope is limited to the function in which they are defined. var
variables are hoisted to the top of their scope during the execution phase, which means you can use the variable before it's declared in the code.var
variables can be redeclared and reassigned.
function variable_declaration() {
var x = 10;
if (true) {
var x = 20; // Same variable as above, not a new one
console.log(x); // Outputs 20
}
console.log(x); // Outputs 20, not 10
} - Variables declared with
-
let
(Block-scoped Declaration):- Variables declared with
let
are block-scoped, meaning their scope is limited to the block (a pair of curly braces) in which they are defined. let
variables are also hoisted, but they are not initialized until the interpreter reaches their declaration in the code.let
variables can be reassigned, but not redeclared in the same scope.
function variable_declaration() {
let x = 10;
if (true) {
let x = 20; // Different variable than the one outside the block
console.log(x); // Outputs 20
}
console.log(x); // Outputs 10, not affected by the inner block
} - Variables declared with
-
const
(Constant Declaration):- Variables declared with
const
are block-scoped likelet
. const
variables must be assigned a value when declared, and that value cannot be changed or reassigned.- Like
let
,const
variables are not hoisted until their declaration.
function variable_declaration() {
const x = 10;
// x = 20; // This would result in an error, as const variables cannot be reassigned
console.log(x); // Outputs 10
} - Variables declared with
In general, it's a good practice to use const
by default and only use let
when you know the variable's value will change. var
is used less frequently in modern JavaScript due to its function-scoping behavior and hoisting quirks. Using const
and let
can help prevent unintended reassignments and improve code clarity.