Lesson 20 of 60 – null and undefined
33%

null and undefined in TypeScript

In TypeScript, null and undefined represent the absence of a value. They are useful when a variable may not contain a value.

Note: null usually represents an intentionally empty value, while undefined commonly means that a value has not been assigned or is unavailable.

1. What is null?

null represents an intentional absence of a value.

let value: null = null;

Here, the variable explicitly contains no value.

2. What is undefined?

undefined usually means that a value has not been assigned.

let value: undefined = undefined;

The variable currently has an undefined value.

3. Difference Between null and undefined

Both represent the absence of a normal value, but they are commonly used in different situations.

let selectedUser: null = null;

let userName: string | undefined;

null can indicate an intentionally empty value, while undefined can indicate that a value has not been assigned.

4. Assigning null

A variable can be assigned null when its type allows null.

let name: string | null = null;

This variable can contain either a string or null.

5. Assigning undefined

A variable can be assigned undefined when its type allows it.

let name: string | undefined = undefined;

The variable can contain a string or undefined.

6. Union Type with null

A union type allows a variable to contain a string or null.

let message: string | null = "Hello";

message = null;

Both assignments are valid.

7. Union Type with undefined

A union type can also allow undefined.

let message: string | undefined = "Hello";

message = undefined;

The variable can contain a string or undefined.

8. Allowing null and undefined

A variable can allow both values using a union type.

let value: string | null | undefined;

value = "Hello";
value = null;
value = undefined;

All three values are allowed.

9. strictNullChecks

TypeScript can use the strictNullChecks compiler option to provide stronger checking for null and undefined.

{
    "compilerOptions": {
        "strictNullChecks": true
    }
}

When enabled, null and undefined are not automatically accepted where another specific type is expected.

10. String and null

If a variable should contain either a string or null, explicitly use a union type.

let username: string | null = null;

username = "Rahul";

This clearly describes the possible values.

11. Number and null

A number variable can also allow null.

let age: number | null = null;

age = 20;

The variable can contain a number or null.

12. Boolean and null

A boolean can also be combined with null.

let loggedIn: boolean | null = null;

loggedIn = true;

This can be useful when the boolean state is not yet known.

13. Checking for null

Use an if statement to check whether a value is null.

let name: string | null = null;

if (name === null) {
    console.log("Name is empty");
}

14. Checking for undefined

You can compare a value with undefined.

let name: string | undefined;

if (name === undefined) {
    console.log("Name is undefined");
}

15. Using typeof with undefined

The typeof operator returns "undefined" for an undefined value.

let value: undefined = undefined;

console.log(typeof value);

The result is "undefined".

16. typeof null

JavaScript has a special behavior for typeof null.

let value = null;

console.log(typeof value);

The result is "object". This is a long-standing JavaScript behavior.

17. Optional Values

Sometimes a value may not be available. In such cases, undefined can represent the missing value.

let phone: string | undefined;

phone = "9876543210";

18. Function Returning null

A function can return either a value or null.

function getUser(): string | null {
    return null;
}

The return type clearly tells us that the function may return a string or null.

19. Function Returning undefined

A function can also return undefined.

function getName(): string | undefined {
    return undefined;
}

The return type describes the possible result.

20. Checking a Function Result

When a function can return null, check the result before using it.

function getUser(): string | null {
    return null;
}

let user = getUser();

if (user !== null) {
    console.log(user.toUpperCase());
}

21. null in React

In React applications, null can be useful when a value is intentionally empty.

let selectedUser: string | null = null;

Later, the selected user can be assigned a string value.

22. undefined in React

An optional value in a React application may be undefined before it becomes available.

let username: string | undefined;

The value can later be assigned.

23. null in React Native

In React Native, null can represent an intentionally empty value, such as no selected item.

let selectedItem: string | null = null;

selectedItem = "Home";

24. undefined in React Native

React Native applications can also have values that are not available yet.

let token: string | undefined;

token = "ABC123";

The type indicates that the value may initially be undefined.

25. null with API Data

An API may return null when a particular value does not exist.

type User = {
    name: string;
    profileImage: string | null;
};

Here, profileImage may contain a URL or intentionally contain null.

26. Optional Property and undefined

An optional property may be absent from an object.

type Student = {
    name: string;
    email?: string;
};

If email is not provided, accessing it can produce an undefined value.

27. Nullish Coalescing Operator

The ?? operator provides a fallback when a value is null or undefined.

let name: string | null = null;

let displayName = name ?? "Guest";

console.log(displayName);

The result is "Guest".

28. Common Mistake

A common mistake is using a value that may be null without checking it.

let name: string | null = null;

// Check before using it
if (name !== null) {
    console.log(name.toUpperCase());
}

Checking first makes the code safer.

29. null and undefined Together

A variable can allow both null and undefined.

let value: string | null | undefined;

value = "Hello";
value = null;
value = undefined;

This is useful when an application needs to distinguish between normal data and missing or empty values.

30. null and undefined Summary

null and undefined are both used for values that are not normal data values.

let name: string | null = null;

let age: number | undefined;

let value: string | null | undefined;

Use union types and appropriate checks when a value can be missing.

📌 Key Points

  • null commonly represents an intentionally empty value.
  • undefined commonly represents an unavailable or unassigned value.
  • Use union types such as string | null when null is allowed.
  • Use string | undefined when a value may be undefined.
  • strictNullChecks provides stronger null and undefined checking.
  • Always check nullable values before using their properties or methods.
  • The ?? operator can provide a fallback for null or undefined.
  • Null and undefined are commonly encountered when working with APIs and React Native data.

🧠 Quick Quiz

Question: Which union type allows a variable to contain either a string or null?