Language: EN

null-y-undefined-en-typescript

Use of Null and Undefined in TypeScript

In TypeScript, both null and undefined represent missing or undefined values. However, while they seem similar in certain aspects, they have distinct meanings and uses.

In summary,

  • Undefined: It is a value that indicates that a variable has been declared but not initialized.
  • Null: It is a value that is explicitly assigned to a variable to indicate the intentional absence of a value.

Usage of Undefined

Declaration and Initialization

When a variable is declared but not initialized, its value is undefined.

let myVariable: string;
console.log(myVariable); // Output: undefined

Functions That Do Not Return Values

Functions that do not have an explicit return statement return undefined by default.

function greet(): void {
    console.log("Hello");
}

const result = greet();
console.log(result); // Output: undefined

Function Parameters

If an argument is not passed to a function, the parameter’s value will be undefined.

function printMessage(message: string) {
    console.log(message);
}

printMessage(); // Error: expected 1 argument, but got 0

Object Properties

Object properties that are not explicitly defined are undefined.

const person = {
    name: "Juan"
};

console.log(person.age); // Output: undefined

Usage of Null

Null Assignment

null must be explicitly assigned to a variable.

let myVariable: string | null = null;
console.log(myVariable); // Output: null

Explicit Initialization

null can be used to initialize variables that are expected to have a value in the future.

let result: number | null = null;
// Code that will assign a value to result
result = 42;
console.log(result); // Output: 42

Strict Null Checks Configuration

When strictNullChecks is enabled in TypeScript, null and undefined are not subtypes of all other types.

This means that a variable of type string cannot contain null or undefined unless explicitly specified.

// tsconfig.json
{
    "compilerOptions": {
        "strictNullChecks": true
    }
}

Type Definitions

Types can be defined that include null and undefined.

let name: string | null = "Juan";
name = null;

let age: number | undefined;
age = 25;
age = undefined;

Common Operations with Null and Undefined

Nullish Coalescing Operator

The nullish coalescing operator (??) allows providing a default value when a variable is null or undefined.

let value: string | null = null;
let message = value ?? "Default value";
console.log(message); // Output: Default value

Optional Chaining Operator

The optional chaining operator (?.) allows accessing properties of objects that may be null or undefined.

const person = {
    name: "Juan",
    address: {
        city: "Madrid"
    }
};

console.log(person.address?.city); // Output: Madrid
console.log(person.contact?.phone); // Output: undefined