Overview
A variable is a symbolic name (identifier) that refers to a value stored in the computer’s memory. Unlike constants, the value held by a variable can be changed (mutated) during program execution.
Core Concepts
- Declaration: Informing the compiler/interpreter that a variable exists (e.g.,
let x;). - Initialization: Assigning an initial value to a variable (e.g.,
x = 10;). - Scope: The region of the program where a variable is accessible (Global, Local, Block scope).
- Type: The kind of data the variable holds (Integer, String, Boolean, etc.), which may be static or dynamic.
Code Examples
// TypeScript/JavaScript
let score = 0; // Declaration and initialization
score = 10; // Reassignment (Mutation)
score += 5; // Update based on current value
console.log(score); // 15
Use Cases
- State Management: Tracking the current status of an application (e.g.,
isLoggedIn,currentUser). - Counters: Managing iterations in loops (e.g.,
for (let i = 0; i < 10; i++)). - Intermediate Calculations: Storing temporary results of a complex mathematical operation.
Gotchas
- Variable Shadowing: Declaring a variable in an inner scope with the same name as one in an outer scope, making the outer one inaccessible.
- Uninitialized Variables: Accessing a variable before it has been assigned a value (e.g.,
undefinedin JS), often leading to runtime crashes. - Global Namespace Pollution: Using too many global variables, which increases the risk of naming collisions and makes debugging difficult.
