Course Banner


TypeScript Functions

TypeScript Functions

Functions are  reusable piece of the code which is written once and called and used in any part of the  application. The task of function is to perform certain fixed work.First, function is defined in any page and then called whenever need be. The benefit of using function is that its written once. We do not need to write same code again and again.

Any function has a  function's name, return type, and parameters.

Example :

1
2
3
4
5
6
function employeeInfo(){
var f_name:string='Rajesh';
console.log('First Name' + f_name);
var l_name:string='Kumar'
console.log('Last Name'+l_name);
}

employeeInfo() // calling of function

The above function is one of the simplest form of function. It does not have parameter passed.

Here is the output:


Function with parameters

Under these kind of functions one or more than one parameters are passed inside function which is also called function signature. Then the same signature value is passed to function body and task is performed.

Example :

Let's modify our previous function example and make it function with parameter.


1
2
3
4
5
6
7
function employeeInfo(fName:string,lName:string){
   var f_name:string=fName;
   console.log('First Name' + f_name);
   var l_name:string=lName
   console.log('Last Name'+l_name);
}
   employeeInfo('Rajesh','Kumar');// function call

In the  above example, we have passed two function parameters called fName and lName. In the function body we have assigned the value of these parameters to our function’s local variable called f_name and l_name and finally we have displayed through console.log .

Output :


Optional Parameters

In our previous program we  have seen that we can pass parameter in the function. That's good but what  if we want to make one of the parameters optional. So, if the value of that parameter is not passed then default value should take.

We can declare a parameter as  optional if we append a question mark to its name. The optional parameter should be set as the last argument in a function.

Example: Optional Parameters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function student_details(roll:number,fullname:string,email:string,mobile?:number) {
 
   console.log("Roll Number:", roll);
  console.log("Full Name",fullname);
 
  if(mobile!=undefined) 
  console.log("Mobile",mobile);
}
student_details(123,'Umar Rahman','saz3sumar@gmail.com');
student_details(111,"Rajesh Kumar",'rajesh@gmail.com',8583959529);

In the above program we have done following :


  • We have declared a function called student_details which  is a parameterized function.

  • It contain 3 parameters as mandatory and the 4th one is optional.

  • If we don't pass any value in mobile number then its value becomes null. And if its null, then it does not show the value.

  • In the second function call, we have passed mobile number also. So, it prints all the 4 values.

And here is the output :


Function with Rest Parameters

If you come  from Java background, you may be aware of  variable arguments. While in the above two examples there were parameters but they were fixed hard coded. Though in the second example, one parameter was optional but still we can type more than 4 values runtime. In case of rest parameter functions ot does not restrict the number of values that you can pass to a function.But one thing you should bear in mind, the value must be passed of same type.

Three dots are placed before any rest parameter. If there is any no rest parameter then it must be placed before the rest parameter.

Example: Rest Parameters

1
2
3
4
5
6
7
8
function YearList(...years:number[]) { 
  var i;  
  for(i = 0;i<years.length;i++) {
   console.log( years[i]);
  }
 }
YearList(2017,2018)
YearList(2015,2015,2017,2018,2019,2020)

  • In the above program you can see we have declared a function called YearList() which parameter is rest this means that it can accept any number of arguments.

  • We have called function two times. First, with two parameters  and other with more than two. And we can see both the function arguments values were accepted successfully.

  • In the  funcion body, we have  used for loop for displaying the array value passed as an arguments. The arguments value passed  is in array format.


Default Parameters

You have already seen optional parameter function. In that function there was one optional parameter in which if the value was not passed,it takes null value as default. But what if we set the default value yourself? Yes, its possible in TypeScript and these kind of functions are called default parameterized functions.One thing you need to bear in mind that  a parameter cannot be declared optional and default at the same time.

Example: Default parameters

1
2
3
4
5
6
7
function employeeList(salary:number,deparment:string,company:string='Suhanasoftech Pvt. Ltd') {
   console.log('Company Name : '+company);
   console.log('Salary : '+salary);
   console.log('Deaprment : '+deparment);
}
employeeList(20000,'Sales')
employeeList(30000,'Technical','Acesoftech Academy')

Output :


  • In the above example, we have declared a function called employeeList with two mandatory parameters and one default parameter.

  • The initial default value of the parameter company we have set as ‘Suhanasoftech Pvt.Ltd’

  • We have invoked the function two times. In the first calling we have skipped company name and it took default.

  • In the second function calling, we have called with company name also. This time, we have passed company name as Acesoftech Academy and the default value ‘Suhanasoftech’ is gone and new value is set.

Anonymous Function

So, far whatever functions we have used in previous examples, all the function have certain name. But there are some cases where you will see unnamed function and these kind of functions are called anonymous functions.  These functions are dynamically declared at runtime. Also, these kind of functions functions can accept inputs and return outputs.

The main thing with anonymous function is that the whole function is assigned to a new variable which is called function expression.

Example :

1
2
3
4
var TypeScript = function() {
  return "I am learning TypeScript"; 
}
console.log(TypeScript())
Output:

Anonymous function with parameters

Just like other functions, anonymous functions also accept parameters.

Below is the example of anonymous functions having parameters.

1
2
3
4
var multi = function(num1:number,num2:number) {
  return num1*num2; 
};
console.log(multi(100,100))

Output :


Difference between function Expression and Function Declaration

One confusion part for any developer is  the difference between function expression and function declaration. The main difference is that a  function expression does not have a function name, on the other hand,a function declaration contains a function name.

The other important difference is that function declarations are parsed before their execution. As contrary to this,a function expressions are parsed only when the script engine encounters it during execution.

Recursion and TypeScript Functions

When we talk about function recursion this means that function is declared  and that function calls itself. In another words, we can say when a function and the caller function is same then we can say it as recursive function.

Example – Recursion

1
2
3
4
5
6
7
8
function factorial(number) {
  if (number <= 0) {         // termination case
     return 1;
  } else {    
     return (number * factorial(number - 1));     // function calling  itself
  }
};
console.log(factorial(12));      //

Example: Anonymous Recursive Function

1
2
3
4
5
(function () {
  var x = "Welcome to Anonymous Function";  
  console.log(x)    
})() 
//() this parenthesis invokes the function itself.

Lambda Functions

Lambda functions are short way to represent an anonymous functions.Since, in this two double arrow is used, its also called Arrow functions.

Example: Lambda Expression

1
2
var msg = (x:number)=>10 + x
console.log(msg(45))      //outputs 55

As you can,lambda functions body statement can also be written in same statement in a concise way.  

Lambda Statement

In lambda function, we can also write its function body which is called lambda statement.

Example:

1
2
3
4
5
var vals = (y:number)=> {   
  y = 10 + y
  console.log(y) 
}
vals(500)


The function’s reference is returned and stored in the variable vals.

Syntactic Variations

Parameter type Inference

One thing you should bear in mind that it's not compulsory to specify data type for parameter. As you know, if you don't specify the  data types, TypeScript consider it as Any data type.

Let's look at following example :

1
2
3
4
5
6
7
8
9
var callMe = (y)=> {
  if(typeof y=="number") {
     console.log(y+" is a number")
  } else if(typeof x=="string") {
     console.log(y+" is a string")
  } 
}
callMe(100)
callMe("Rajesh")

Optional parentheses for a single parameter

1
2
3
4
var newOp = a=> { // as you can see we have not written =>a() like this
  console.log("This is the value t "+a)
}
newOp(500)

Output :

Empty parentheses for no parameter

1
2
3
4
var myFunc =(y)=> {
  console.log("Function invoked");
}
myFunc(300)

Function Overloads

If you are from JAVA or C, C++ background you may be aware of function overloading.So, what is function overloading? When function name is same but its signature is different, it's called function overloading.

Function can be overloaded  with following ways :

  1. With data type :  

function overload(string):void;
function overload(number):void;

In the above code snippet, function name is same but the parameters data type are different.

2. With number of parameters

function overload(n1:number):void;
function overload(x:number,y:number):void;
In the above code snippet,as you can see the number of parameters are different. But the function name is same.


3. The sequence of parameters

function overload(n1:number,s1:string):void;
function overload(s:string,n:number):void;

In the above program you can see the sequence of parameters are different. Though number of parameters and type of parameters are different.

Example

Let us now take a look at the following example code

1
2
3
4
5
6
7
8
9
function course(cname:string):void;
function course(fees:number,cname:string):void;
 
function course(a:any,b?:any):void {
  console.log(a);
  console.log(b);
}
course("JAVA")
course(20000,"Angular js");

Output :


Ad Image