In TypeScript, both null and undefined represent missing or not defined values. However, while they may seem similar in certain 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.
Use of undefined
Declaration and Initialization
When a variable is declared but not initialized, its value is undefined.
let myVariable: string;
console.log(myVariable); // Output: undefinedFunctions 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: undefinedFunction parameters
If an argument is not passed to a function, the value of the parameter will be undefined.
function printMessage(message: string) {
console.log(message);
}
printMessage(); // Error: Expected 1 argument, but got 0Object properties
Object properties that are not explicitly defined are undefined.
const person = {
name: "Luis"
};
console.log(person.age); // Output: undefinedUse of null
Assignment of null
null must be explicitly assigned to a variable.
let myVariable: string | null = null;
console.log(myVariable); // Output: nullExplicit 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: 42Strict 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 that include null and undefined can be defined.
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 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 valueOptional chaining operator
The optional chaining operator (?.) allows accessing properties of objects that may 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