Static vs Dynamic Typing — Explained with Examples
Static typing requires that variable types be known at compile time. The compiler verifies type correctness before the program runs, catching type errors early. Languages like Java, C++, TypeScript, Go, and Rust are statically typed. Dynamic typing defers type checking to runtime; variables can hold values of any type, and type errors only surface when the offending code is executed. Python, JavaScript, Ruby, and PHP are dynamically typed.
Static typing offers faster execution (type information enables optimizations), better IDE support, and compile-time error detection. Dynamic typing offers flexibility, faster prototyping, and simpler code for small projects. Gradual typing systems (TypeScript, Python type hints, MyPy) attempt to bridge the gap. Neither is strictly superior — the choice depends on project scale, team preferences, and performance requirements.
Real-world analogy. Static typing is like a parking garage with height-limited barriers. Before you enter (compile), the garage checks your car’s height. If your SUV is too tall, you’re stopped immediately — no risk of getting stuck inside. Dynamic typing is like an open parking lot: any vehicle can enter freely (run), but an SUV might crash into a low overhang inside.
Example (TypeScript — static):
let name: string = "Alice";
name = 42; // Compile error: Type 'number' not assignable to 'string'
Example (JavaScript — dynamic):
let name = "Alice";
name = 42; // Perfectly fine — type is checked at runtime
Related terms: Strong vs Weak Typing, Compiled vs Interpreted, TypeScript, JIT Compilation, Transpiler
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro