Lesson 2 +10 XP

Static vs Dynamic Typing

Static vs Dynamic Typing

JavaScript is dynamically typed, meaning variable types are checked at runtime. TypeScript brings static typing, checking variable types during compilation.

Comparison Overview

AspectDynamic Typing (JavaScript)Static Typing (TypeScript)
Type CheckingOccurs at runtimeOccurs at compile time
Variable ReassignmentVariable can hold any type at any timeVariable has a fixed or constrained type
Bug DiscoveryUsers may trigger runtime errorsDeveloper discovers errors while editing
Build StepNo compilation neededCompilation step required

Example Code Comparison

In JavaScript:

let user = "Alice";
user = 42; // Allowed in JS, can cause unexpected bugs downstream
console.log(user.toUpperCase()); // Runtime TypeError: user.toUpperCase is not a function

In TypeScript:

let user: string = "Alice";
user = 42; // Error: Type 'number' is not assignable to type 'string'.

TL;DR

  • Dynamic languages check types during execution; static languages check types during compilation.
  • Static typing catches bug classes like misspelled properties and null pointer references early.