TypeScript

5.3. Difference Between var, let, and const in TypeScript / JavaScript

πŸš€ 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.

Leave a Reply

Your email address will not be published. Required fields are marked *