Diferance between var, let , const in javascript
In JavaScript, var
, let
, and const
are used to declare variables, but they differ in scope, hoisting, and mutability.
Here's a breakdown:
1. var
- Scope:
- Function-scoped: A
var
variable is available within the function it is defined in. - It ignores block scope (e.g.,
if
orfor
blocks).
- Function-scoped: A
- Hoisting:
- Variables declared with
var
are hoisted to the top of their scope but are initialized withundefined
. This means you can access the variable before its declaration, but its value will beundefined
. - console.log(x); // undefinedvar x = 5;
- Allowed within the same scope.
- Example:var a = 10;var a = 20; // No error Use: Considered outdated and rarely used in modern code.
let
- Scope:
- Block-scoped: A
let
variable is only available within the block it is defined in (e.g., inside{}
).
- Block-scoped: A
- Hoisting:
- Variables declared with
let
are hoisted but are not initialized. Accessing them before declaration results in aReferenceError
due to the "temporal dead zone."console.log(y); // ReferenceErrorlet y = 10; - Redeclaration:
- Not allowed within the same scope.let b = 10;let b = 20; // SyntaxError: Identifier 'b' has already been declared
- Use: Preferred for variables that will be reassigned.
3.const
- Scope:
- Block-scoped, like
let
.
- Block-scoped, like
- Hoisting:
- Same as
let
, with a temporal dead zone.console.log(z); // ReferenceErrorconst z = 15; - Redeclaration:
- Not allowed.
- Not allowed.
- Reassignment:
- Variables declared with
const
cannot be reassigned.const c = 30;c = 40; // TypeError: Assignment to constant variable. - Mutability:
- If the variable is an object or an array, you can modify its properties or elements (mutate), but you cannot reassign the entire object or array.const obj = { name: "Alice" };obj.name = "Bob"; // Allowedobj = { name: "Charlie" }; // TypeError
- Use: Best for values that should not be reassigned, such as constants or configuration values.
- If the variable is an object or an array, you can modify its properties or elements (mutate), but you cannot reassign the entire object or array.
Summary Table
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Hoisted (initialized to undefined ) | Hoisted (not initialized) | Hoisted (not initialized) |
Redeclaration | Allowed | Not allowed | Not allowed |
Reassignment | Allowed | Allowed | Not allowed |
Use Cases | Legacy code | Reassignable variables | Constants and immutable references |
In modern JavaScript, it's recommended to use let
and const
instead of var
. Use const
by default, and switch to let
only when reassignment is necessary.