Variables and Immutability
Intro to Variables
Variables are containers for values. In TypeScript (and modern JavaScript), you
have two main ways to declare them:
let and const.let count = 0 // Can be reassigned
const name = 'Alice' // Cannot be reassigned
When to Use Each
Use
const by default. It signals that this binding won't change, making
your code easier to understand.Use
let when you need to reassign. Loop counters, accumulators, and state
that changes over time.const TAX_RATE = 0.08 // Never changes
let total = 0 // Will be updated
for (const item of items) {
total += item.price // Reassigning total
}
Reassignment vs Mutation
An important distinction:
- Reassignment - Pointing the variable to a new value
- Mutation - Changing the contents of the existing value
let arr = [1, 2, 3]
arr = [4, 5, 6] // Reassignment - arr points to a NEW array
arr.push(7) // Mutation - modifying the SAME array
const prevents reassignment but NOT mutation. You can still modify the
contents of a const array or object.Understanding this distinction helps you write predictable, bug-free code.
You might encounter
var in older JavaScript code. It's the original way to
declare variables, but it has confusing scoping rules (function scope instead
of block scope) and allows redeclaration. Modern JavaScript introduced let
and const specifically to fix these issues. There's no reason to use var
in new code, which is why we focus exclusively on let and const.๐ For more details, see MDN's guide on variable
declarations.
Exporting Variables
In this and future exercises, you'll be required to see the
export
variables. This makes the variable available to other files. It's how the app
displays your values and how tests verify your solutions. For now, just know
that export shares your variable with the outside world.Example of exporting a single variable:
export const FAVORITE_COLOR = 'blue'
Example of exporting multiple variables:
const FAVORITE_COLOR = 'blue'
let currentAge = 25
export { FAVORITE_COLOR, currentAge }
We'll cover modules in depth later in the workshop series.