π Difference Between var
, let
, and const
in TypeScript / JavaScript
In TypeScript (and JavaScript), you have three ways to declare variables: var
, let
, and const
. Although they all seem similar, there are important differences in how they behave in terms of scope, hoisting, and mutability.
β
1. var
β The Traditional Way
π Use:
- Used to declare variables globally or locally to an entire function.
- Function-scoped.
- Hoisted to the top of its scope, but not initialized.
π Behavior:
- If declared outside a function β Global scope.
- If declared inside a function β Local to the function.
- Accessible even before declaration due to hoisting (but value is
undefined
).
π§ Example:
function testVar() {
console.log(x); // undefined
var x = 10;
console.log(x); // 10
}
testVar();
β οΈ Pitfall:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 3, 3, 3 β because `var` is function-scoped, not block-scoped.
β
2. let
β Modern, Block-Scoped
π Use:
- Introduced in ES6 (and TypeScript) to overcome issues with
var
. - Block-scoped (limited to
{}
). - Not hoisted the same way as
var
.
π Behavior:
- Not accessible before declaration (Temporal Dead Zone).
- Preferred when the variable value may change.
- Safer and more predictable than
var
.
π§ Example:
function testLet() {
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10
}
testLet();
β
Solution to earlier var
pitfall:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 0, 1, 2 β Each iteration has its own block scope.
β
3. const
β Constant, Block-Scoped
π Use:
- Used to declare a constant β a variable that cannot be reassigned.
- Also block-scoped.
- Must be initialized when declared.
π Behavior:
- Cannot be reassigned.
- Can be used for global constants.
- Still mutable for object properties or array contents (but not the variable itself).
π§ Example:
const PI = 3.14159;
// PI = 3.14; β Error: Cannot assign to 'PI'
const arr = [1, 2, 3];
arr.push(4); // β
Allowed: internal mutation
console.log(arr); // [1, 2, 3, 4]
π Summary Table
Feature | var |
let |
const |
---|---|---|---|
Scope | Function | Block | Block |
Hoisting | Yes (initialized to undefined ) |
No (Temporal Dead Zone) | No (TDZ) |
Reassignable | Yes | Yes | β No |
Redeclarable | Yes | β No (in same scope) | β No (in same scope) |
Initialization | Optional | Optional | β Required |
Use Case | Legacy support | Variable that changes | Constants |
π§ Quick Best Practices
- Use
const
by default. - Use
let
only if the variableβs value will change. - Avoid
var
unless maintaining legacy code.
π» 5 Programming Assignments on var
, let
, and const
π§© Assignment 1: Temperature Converter with
let
Write a TypeScript program that converts Celsius to Fahrenheit using the formula:
F = C Γ 9/5 + 32
β
Use let
for all variables since values may change during calculation.
β
Input can be hardcoded or prompted.
π§© Assignment 2: Constant Pi Area Calculator
Create a program to calculate the area of a circle using the formula:
Area = Ο Γ rΒ²
β
Use const
for Ο = 3.14159
β
Use let
for radius and area
β
Print the result with a clear message.
π§© Assignment 3: Loop with
let Index
Write a loop that prints numbers 1 to 5.
Inside the loop, create a variable that stores the square of the number.
β
Use let
for both the loop index and square variable.
β
Avoid using var
.
π§© Assignment 4: Object Modification with
const
Create a const
object for a car:
const car = { brand: "Toyota", year: 2020 };
Modify the year
property to 2025 and print the updated object.
β
Do not reassign the object, just modify it.
β
Print both before and after the change.
π§© Assignment 5:
var vs
let in Loop Scope
Write a program using var
inside a for
loop, then repeat using let
. After the loop ends, try to print the loop variable.
β
Compare what gets printed for var
and let
β
This helps observe scope differences.