Open In App

TypeScript void Function

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Void functions in TypeScript are functions that do not return a value. They perform actions or computations without producing a result that needs to be captured. Commonly used for side effects like logging, modifying external state, or triggering asynchronous operations, they enhance code clarity.

Syntax:

function functionName(parameters: ParameterType): void {
    // Function body
    // No return statement or return type annotation is needed
}

Where:

  • functionName is the name of the function.
  • parameters are optional parameters that the function may accept.
  • void is the return type annotation that indicates that the function doesn't return a value.

Examples of Void Functions in TypeScript

Example 1: Simple Void Function

In this example, the greet function is a void function. It takes one parameter, name, which is a string. The function logs a greeting message to the console and does not return a value.

JavaScript
function greet(name: string): void {
    console.log(`Hello, ${name}!`);
}

greet("GeeksforGeeks");

Output:

Hello, GeeksforGeeks!

Example 2: Void Function with a Loop

In this example, the logEvenNumbers function is a void function that takes one parameter, max, which is expected to be a number. Inside the function, it iterates through numbers from 0 to max and logs each even number to the console. Since it's a void function, it doesn't return a value.

JavaScript
function logEvenNumbers(max: number): void {
    for (let i = 0; i <= max; i++) {
        if (i % 2 === 0) {
            console.log(i);
        }
    }
}

logEvenNumbers(10);

Output:

0
2
4
6
8
10

Conclusion

In this article, we discussed what a void function is and how to use it in TypeScript. Essentially, a void function indicates that the function performs some actions or computations but doesn't produce a result that needs to be used or captured. Void functions are often used for operations that have side effects, such as logging to the console, modifying external state, or triggering asynchronous operations.


Next Article

Similar Reads