Understanding Var, Let, and Const
In JavaScript, var
, let
, and const
are used to declare variables, but they have some key differences in terms of scope, hoisting, and mutability. Here are the main differences along with code examples:
var
:
-
- Function-scoped: Variables declared with
var
are function-scoped, which means they are accessible throughout the entire function where they are declared. - Hoisting: Variables declared with
var
are hoisted to the top of their containing function or global scope. - Mutable:
var
variables can be reassigned and updated.
- Function-scoped: Variables declared with
function exampleLet() { if (true) { let y = 20; } // console.log(y); // ReferenceError: y is not defined } exampleLet();
let
:
- Block-scoped: Variables declared with
let
are block-scoped, meaning they are only accessible within the block they are defined in. - Hoisting:
let
variables are hoisted to the top of their block but are in a “temporal dead zone” until the declaration is reached. - Mutable:
let
variables can be reassigned and updated.
function exampleLet() { if (true) { let y = 20; } // console.log(y); // ReferenceError: y is not defined } exampleLet();
const
:
- Block-scoped: Like
let
,const
is block-scoped. - Hoisting:
const
variables are hoisted to the top of their block but, likelet
, they are in a “temporal dead zone” until the declaration is reached. - Immutable:
const
variables cannot be reassigned. However, if the variable holds an object or array, the properties or elements of that object or array can still be modified.
function exampleConst() { if (true) { const z = 30; } // console.log(z); // ReferenceError: z is not defined } exampleConst(); const fruits = ['apple', 'banana']; fruits.push('cherry'); // This is allowed // fruits = []; // Error: Assignment to a constant variable
In general, it’s a good practice to use const
by default for variables that don’t need reassignment.
Use let
when you need a variable that will change its value, and avoid using var
as it has some quirks and is considered outdated in modern JavaScript.
0 Comments