TypeScript
/Beginner
null & undefined
Definition
`undefined` means a variable has been declared but has not yet been assigned a value. `null` is an assignment value representing no value or no object.
Explain Like I'm New
`undefined` is a drawer that you just built but haven't put anything inside yet. `null` is opening the drawer and finding a specific note that says 'This drawer is intentionally empty'.
Real World Example
In a database query, `findUser()` returns `null` if the user is not found. An optional config parameter is `undefined` if the developer didn't pass it.
Common Use Cases
- •Representing missing data
- •Strict Null Checks configuration in TS
Interactive Example
// With strictNullChecks: true (Best Practice) let username: string; // username = null; // Error: Type 'null' is not assignable to type 'string' let optionalUser: string | null = null; // Correct way to handle missing data function printName(name: string | undefined) { // Must check before using string methods! if (name !== undefined) { console.log(name.toUpperCase()); } }
Interview Questions
basic
- What is the difference between null and undefined?
intermediate
- What does the `strictNullChecks` flag do in tsconfig?
advanced
- What is the Non-Null Assertion Operator `!`?