Open In App

TypeScript void Function

TypeScript is a popular programming language used for building scalable and robust applications. TypeScript void function is a function that doesn’t return any value, or returns undefined.

Syntax:

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

Where:



Example 1: In this example, function greet is the name of the function which is a void function, the name is the parameter, and its type is a string, indicating that the function expects a string argument.






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

Output:

Example 2: In this example, logEvenNumbers 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.




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

Output:

Conclusion: In this article we have discussed about what is void fucntion and how to use it. Essentially, it indicates that the function performs some actions or computations but doesn’t produce a result that needs to be used or captured. It’s often used for functions that have side effects like logging into the console, modifying external state, or triggering asynchronous operations.

Reference: https://www.typescriptlang.org/docs/handbook/2/functions.html#void


Article Tags :