Functions in TypeScript

  • Functions are a set of statements that we can reuse multiple times at different places within our project.
  • Functions perform a specific task, which can be simple as well as complex.
  • Statements within a function are not executed on their own until the function is called. This process is known as function invocation.
  • We can divide our program into functions which makes the program readable and help in maintaining it.
  • We have to specify the name of the function (which follows the rules of identifier), return type and parameters (if any).

Below is the syntax of the function:

function functionName(){
   /* Function Definition
      Statements or code that will be executed 
      when this function is called */
}

For example:

function hello(){
    console.log("Inside hello function");
}
Function Invocation
hello(); //function invocation

// writing a function
function hello(){
    // function definition
    console.log("Inside hello function");
}

Below is the output of above code:

Function returning a value
  • In above examples, we are just displaying the message.
  • There can be a requirement when we want to return something from a function as use it somewhere else, say want to perform an operation and return the result.
  • The return data type can be any data type, but it should match the data type of that value that you are returning from the function.
  • Function should end with a return statement. As soon as the control of the function encounters a return statement, it will execute that return statement and the control goes back to the statement from the function was initially invoked. It will not execute the statements after that return.
  • There can only be one return value, however there can be multiple return statements. For example, if there is a statement with if…else statement, we can put return statement in both if and else.
  • We can invoke a function from another function.
    Below is the syntax:
function functionName():returnDataType{
    // Statements
       return value;
}

Below is an example. Here, we are defining two functions, hello (which does not return a value) and add (which returns the sum of two numbers). add() function in invoked from another function, hello().

hello(); //function invocation

// writing a function
function hello(){
    // function definition
    console.log("Inside hello function");
    var sum=add(); //another function is called from a function
    console.log("Sum is: " + sum);
}

function add():number{
    var num1:number=10;
    var num2:number=20;
    return (num1+num2);
}

Below is the output of above code:

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Design a site like this with WordPress.com
Get started