Open In App

TypeScript void Function

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • 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.

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.

Javascript




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


Output:z57

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.

Javascript




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


Output:z58

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads