Dynamic typing
What is typing
Typing is the way a programming language manages data types (numbers, strings, objects, and so on).
Static vs Dynamic typing
| Characteristic | Static typing | Dynamic typing |
|---|---|---|
| When the type is determined | At compile time | At run time |
| Can the variable's type change | No | Yes |
| Example languages | TypeScript, Java, C#, C++ | JavaScript, Python, PHP |
| Type checking | Before the program runs | During execution |
| Error type on mismatch | Compilation error | Runtime error |
Example: JavaScript (dynamically typed)
javascript
let value = 42; // number
console.log(typeof value); // "number"
value = "Hello"; // now a string!
console.log(typeof value); // "string"
value = true; // now a boolean value
console.log(typeof value); // "boolean"Here, the variable's type can change at runtime, and this is normal for JS.
Comparison example: TypeScript (statically typed)
javascript
let value: number = 42;
value = "Hello"; // Error: type "string" is not assignable to type "number"In TypeScript (or Java), the type is specified once and cannot change.
Consequences of dynamic typing
Pros:
- Faster code writing, fewer "noisy" annotations.
- Flexibility: variables can be reused with different types.
Cons:
- Errors only show up at runtime.
- Harder to debug large projects.
- Unexpected type conversions are possible:
javascript
console.log('5' - 2); // 3 (string → number)
console.log('5' + 2); // "52" (number → string)Summary
JavaScript is a dynamically and weakly typed language, because:
- the variable's type is determined at runtime,
- and can change at any moment,
- while the language automatically converts types when possible.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.