TypeScript Course
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 `!`?

Flash Cards

Question

What does strictNullChecks do?

Click to reveal answer
Answer

If `strictNullChecks` is false, TS allows you to assign `null` to a variable typed as `string`. This is terrible and causes bugs. If true, `string` means ONLY string, and you must explicitly allow nulls using a union type: `string | null`.

Question

What is the Non-Null Assertion Operator '!'?

Click to reveal answer
Answer

If TS warns that a value might be null, but YOU know for a 100% fact it is not (e.g., getting an element by ID that is hardcoded in the HTML), you append `!` to tell TS to shut up: `document.getElementById('app')!.innerHTML`.