What is dynamic typing?

Dynamic typing means types belong to values, not variables: a variable can hold a number now and a string later, and type checks happen at runtime instead of before the program runs.

What it looks like

let x = 5; x = "five"; x = { five: 5 }; is perfectly valid. Functions accept any arguments, and errors such as calling something that is not a function only appear when that line actually runs.

Strengths

  • Fast to write and prototype.
  • Flexible data handling (JSON from APIs, plugins, duck typing: "if it has a .then, treat it like a promise").
  • No compile step required.

Weaknesses

  • Type errors show up late, often in production, in code paths tests missed.
  • Refactoring is riskier: renaming a property cannot be checked automatically.
  • Implicit coercion can produce wrong values instead of errors ("2" + 1).

How teams manage it

  • TypeScript adds static types that are checked at build time and erased at runtime. It is the default for most professional front-end work today.
  • Runtime validation at boundaries (API responses, form input, localStorage) with schema libraries like Zod, because static types cannot verify data that arrives at runtime.
  • JSDoc type annotations for projects that stay in plain JavaScript.
  • Defensive checks with typeof, Array.isArray, Number.isFinite.

Dynamic vs weak typing

They are different ideas. Dynamic is about when types are checked; weak typing is about implicit conversions. JavaScript is both dynamic and fairly weakly typed. Python is dynamic but stricter about conversions.

Code example

js
1let value = 42;
2console.log(typeof value); // number
3value = "forty-two";
4console.log(typeof value); // string
5value = { answer: 42 };
6console.log(typeof value); // object
7
8// Errors only appear when the line runs
9function shout(text) {
10 return text.toUpperCase();
11}
12console.log(shout("hi")); // HI
13try {
14 shout(123);
15} catch (e) {
16 console.log(e.name, "-", e.message); // TypeError - text.toUpperCase is not a function
17}
18
19// Duck typing: check capabilities, not types
20const isThenable = (x) => x != null && typeof x.then === "function";
21console.log(isThenable(Promise.resolve()), isThenable({ then() {} }), isThenable(42)); // true true false
22
23// Runtime validation at a boundary
24function parseUser(data) {
25 if (typeof data?.name !== "string" || !Number.isInteger(data?.age)) {
26 throw new TypeError("Invalid user payload");
27 }
28 return { name: data.name, age: data.age };
29}
30console.log(parseUser({ name: "Ada", age: 36 }));
31try {
32 parseUser({ name: "Ada", age: "36" });
33} catch (e) {
34 console.log(e.message); // Invalid user payload
35}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app