TypeScript – null vs. undefined


TypeScript – null vs. undefined


”;


In TypeScript, ”undefined” denotes that a variable has been declared but has not been assigned any value. On the other hand, ”null” refers to a non-existent object which is basically ”empty” or ”nothing”.

Have you ever faced a scenario where you need to declare the variable but need to initialize it later? It generally happens while dealing with the APIs where you need to initialize the variables after getting an API response. In such cases, you can use the null or undefined data types to represent the absence of values.

What is null?

In TypeScript, ”null” is a primitive value, which represents the no value assigned to the variable. It is explicitly assigned to the variable to indicate the variable is empty or doesn”t contain any value.

Let”s understand how to use the ”null” in TypeScript via the examples below.

Example: Basic use of null

In the code below, we have defined a variable of ”null” type. It represents the variable ”a” contains an empty value. In the output, you can observe that it prints a null value.

// Using null value
let a: null = null;
console.log(a); // null

On compiling, it will generate the following JavaScript code.

// Using null value
let a = null;
console.log(a); // null

The ouput of the above code is as follows –

null

Example: Data type of null

The data type of the ”null” type variable is an object.

Here, we have used the ”typeof” operator to check the data type of the variable containing the null value. It returns the object which you can observe in the output.

let a: null = null;
console.log(typeof a); // Object

On compiling, it will generate the following JavaScript code.

let a = null;
console.log(typeof a); // Object

The output of the above code is as follows –

object

Example: Reinitializing null variable

In the code below, the data type of the variable ”a” is either number or null. Initially, we have assigned a null value to that. After that, we have assigned the number value to the variable ”a”.

let a: number | null = null;
console.log("The initial value of the variable a is: " + a); // null
a = 10;
console.log("The value of the variable a is: " + a); // 10

On compiling, it will generate the following JavaScript code.

let a = null;
console.log("The initial value of the variable a is: " + a); // null
a = 10;
console.log("The value of the variable a is: " + a); // 10

Its output is as follows –

The initial value of the variable a is: null
The value of the variable a is: 10

What is undefined?

When you declare the variable but don”t assign any value, TypeScript automatically assigns the ”undefined” value to the variable. Whenever you don”t return anything from the function, it returns the undefined value. However, you can also explicitly assign an undefined value to the variable of type ”undefined”.

Let”s understand about undefined via the examples below.

Example: Undefined Values

In the code below, we have defined the variable ”a” but haven”t initialized it with the value. So, its value is undefined which you can see in the output.

let a: number;
console.log("The value of a is " + a);

On compiling, it will show the following error –

Variable ''a'' is used before being assigned.

And also it will generate the following JavaScript code.

let a;
console.log("The value of a is " + a);

The output of the above JavaScript code is as follows –

The value of a is undefined

Example: Not returning a value from the function

In the code below, we have defined the greet() function which doesn”t return any value.

After that, we invoked the greet() function and stored its outcomes in the variable ”a”. The value of the variable is undefined as the greet() function doesn”t return any value.

// Not returning a value from the function
function greet(name: string): void {
    console.log(`Hello ${name}`);
}
let a = greet(''John'');
console.log(a); // undefined

On compiling, it will generate the following JavaScript code.

// Not returning a value from the function
function greet(name) {
    console.log(`Hello ${name}`);
}
let a = greet(''John'');
console.log(a); // undefined

The output of the above code is as follows –

Hello John
Undefined

Example: Using the undefined type

Here, we have used the ”undefined” data type with the variable ”a” and assigned an undefined value to it.

The type of the variable ”a” is undefined but not object as like the ”null” type variables.

let a: undefined = undefined;
console.log(a); // undefined
console.log(typeof a); // undefined

On compiling, it will generate the following JavaScript code.

let a = undefined;
console.log(a); // undefined
console.log(typeof a); // undefined

The output is as follows –

undefined
undefined

Null vs. Undefined: Key Differences

You learned about Null and Undefined. Now, let”s look at the key differences between them.

Feature null undefined
Meaning Explicitly no value Not initialized
Typical Use Intentionally empty or absent value Variable declared but not yet assigned
Type Annotation Has its own type null Has its own type undefined
Default Behavior Does not trigger default function parameters Triggers default function parameters
Function Parameters Used to denote explicitly that parameter should not have a value Indicates missing parameters or optional parameters
Object Properties Can be used to indicate properties that are deliberately set to no value Used for properties that may not be initialized
Operational Handling Must be handled explicitly in logic to avoid errors Often handled with default values or optional chaining

Let”s look at the examples below which shows where to use null and undefined values.

Example: Object Properties

In the code below, the ”user” type has ”name”, ”age”, and ”email” properties. The ”age” property can accept a null value if the user”s age is not available. The ”email” property is optional so it”s fine if we don”t use it while defining the object.

The ”user1” object contains the ”age” property with the null value. The ”user2” value doesn”t contain the ”email” property. So, it is undefined for the ”user2” object.

type User = {
    name: string;
    age: number | null;
    email?: string;
  };
  
  let user1: User = {
    name: "John Doe",
    age: null, // Explicitly no age provided
    email: "[email protected]"
  };
  
  let user2: User = {
    name: "Jane Doe",
    age: 25
    // email is optional and thus can be undefined
  };
  
  console.log(user1); // Output: { name: "John Doe", age: null, email: "[email protected]" }
  console.log(user2); // Output: { name: "Jane Doe", age: 25 }

On compiling, it will generate the following JavaScript code.

let user1 = {
    name: "John Doe",
    age: null, // Explicitly no age provided
    email: "[email protected]"
};
let user2 = {
    name: "Jane Doe",
    age: 25
    // email is optional and thus can be undefined
};
console.log(user1); // Output: { name: "John Doe", age: null, email: "[email protected]" }
console.log(user2); // Output: { name: "Jane Doe", age: 25 }

The output of the above code is as follows –

{ name: ''John Doe'', age: null, email: ''[email protected]'' }
{ name: ''Jane Doe'', age: 25 }

This way, you can either use the null or undefined to present the absence of the values in the code.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *