let, var, and const with examples in ES6 | Lecture 2
In
JavaScript, let, var, and const are used to declare variables,
but they behave differently in terms of scope, reassignment, and hoisting.
Here's an explanation of each with examples:
1. var
- Scope: var is function-scoped, meaning
it is accessible throughout the function where it is declared.
- Reassignment: Variables declared with var can be reassigned and
re-declared.
- Hoisting: var declarations are hoisted to
the top of their scope and initialized with undefined.
Example:
// Hoisting
console.log(a); // Output: undefined
var a = 10;
// Function scope
function testVar() {
var x = 5;
if (true) {
var x =
10; // Same variable as above
console.log(x); // Output: 10
}
console.log(x); // Output: 10
}
testVar();
2. let
- Scope: let is block-scoped, meaning it
is accessible only within the block, statement, or expression where it is
declared.
- Reassignment: Variables declared with let can be reassigned but not
re-declared within the same scope.
- Hoisting: let is hoisted but not
initialized, so accessing it before declaration results in a ReferenceError.
Example:
// Hoisting
// console.log(b); // ReferenceError: Cannot access
'b' before initialization
let b = 20;
// Block scope
function testLet() {
let y = 5;
if (true) {
let y =
10; // Different variable from the outer y
console.log(y); // Output: 10
}
console.log(y); // Output: 5
}
testLet();
3. const
- Scope: const is block-scoped like let.
- Reassignment: Variables declared with const cannot be reassigned.
However, if the variable holds an object or array, the contents can be
modified.
- Hoisting: const is hoisted but not
initialized, so accessing it before declaration results in a ReferenceError.
Example:
// Hoisting
// console.log(c); // ReferenceError: Cannot access
'c' before initialization
const c = 30;
// Block scope and reassignment
function testConst() {
const z =
15;
if (true) {
const z =
25; // Different variable from the outer z
console.log(z); // Output: 25
}
console.log(z); // Output: 15
// z = 20;
// TypeError: Assignment to constant variable
}
testConst();
// Modifying objects
const obj = { name: "John" };
obj.name = "Doe"; // Allowed
console.log(obj); // Output: { name:
"Doe" }
Key Differences
|
Feature |
var |
let |
const |
|
Scope |
Function-scoped |
Block-scoped |
Block-scoped |
|
Reassignment |
Allowed |
Allowed |
Not
allowed (for primitive values) |
|
Re-declaration |
Allowed |
Not
allowed |
Not
allowed |
|
Hoisting |
Hoisted
and initialized to undefined |
Hoisted
but uninitialized (throws error if accessed early) |
Hoisted
but uninitialized (throws error if accessed early) |
When to Use
- var: Rarely used in modern
JavaScript due to scope issues. Use let or const instead.
- let: Use when the value of the
variable will change.
- const: Use for constants or when
you don't intend to reassign the variable. It’s preferred in most cases
for better code reliability.
Comments
Post a Comment