JavaScript Variables can be declared in 4 ways:
- Automatically
- var
- let
- const
1. Automatically
They are automatically declared when first used:
x = 5;
y = 6;
z = x + y; // Output: 11
2.var
- Scope: Function-scoped or globally scoped if declared outside any function.
- Re-declaration: Allows re-declaration within the same scope, which can lead to unexpected behavior.
- Hoisting: Variables declared with
varare hoisted to the top of their scope (but only their declaration, not their initialization).
Example:
var name = "Alice";
var name = "Bob"; // No error, allowed in the same scope
3. let
- Scope: Block-scoped, meaning it’s only accessible within the
{ }it was defined in. - Re-declaration: Cannot be re-declared within the same scope, helping to avoid errors.
- Hoisting:
letvariables are also hoisted, but unlikevar, they are not initialized. They enter a “temporal dead zone” from the start of the block until their declaration, which prevents access before they are declared.
Example:
let age = 25;
let age = 30; // Error: can't re-declare in the same scope
3. const
- Scope: Block-scoped, similar to
let. - Re-declaration: Cannot be re-declared or reassigned within the same scope.
- Initialization: Must be initialized at the time of declaration, as it cannot be assigned later.
- Immutability: The variable itself is immutable (i.e., it can’t be reassigned), but if it’s an object or array, the properties or elements inside can be modified.
Example:
const city = "New York";
city = "Los Angeles"; // Error: cannot reassign a `const` variable
Summary
| Keyword | Scope | Re-declaration | Reassignment | Hoisting |
|---|---|---|---|---|
var | Function / Global | Allowed | Allowed | Yes (initially undefined) |
let | Block | Not allowed | Allowed | Yes (in “temporal dead zone”) |
const | Block | Not allowed | Not allowed | Yes (in “temporal dead zone”) |


Leave a Reply