In TypeScript, both null and undefined represent missing or undefined values. However, although they may seem similar in some aspects, they have distinct meanings and uses.
In summary,
- Undefined: It is a value that indicates 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.
Using 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: "Luis"
};
console.log(person.age); // Output: undefined
Using null
Assignment of null
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
strictNullChecks Configuration
When strictNullChecks is enabled in TypeScript, null and undefined are not subtypes of all other types.
This means a variable of type string cannot contain null or undefined unless explicitly specified.
// tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
Type Definitions
You can define types that include null and undefined.
let name: string | null = "Luis";
name = null;
let age: number | undefined;
age = 25;
age = undefined;
Common Operations with null and undefined
Nullish Coalescing Operator
The nullish coalescing operator (??) allows you to provide 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 might be null or undefined.
const person = {
name: "Luis",
address: {
city: "Madrid"
}
};
console.log(person.address?.city); // Output: Madrid
console.log(person.contact?.phone); // Output: undefined
