TypeScript Function

Functions are the fundamental building block of any applications in JavaScript. It makes the code readable, maintainable, and reusable. We can use it to build up layers of abstraction, mimicking classes, information hiding, and modules. In TypeScript, however, we have the concept of classes, namespaces, and modules, but functions still are an integral part in describing how to do things. TypeScript also allows adding new capabilities to the standard JavaScript functions to make the code easier to work.

Advantage of function

These are the main advantages of functions.

  • Code reusability: We can call a function several times without writing the same block of code again. The code reusability saves time and reduces the program size.
  • Less coding: Functions makes our program compact. So, we don't need to write many lines of code each time to perform a common task.
  • Easy to debug: It makes the programmer easy to locate and isolate faulty information.

Function Aspects

There are three aspects of a function.

  1. Function declaration
  2. Function definition
  3. Function call
  • Function declaration: A function declaration tells the compiler about the function name, function parameters, and return type. The syntax of the function declaration is:
Syntax
function functionName( [arg1, arg2, ...argN] );
  • Function definition: It contains the actual statements which are going to executes. It specifies what and how a specific task would be done. The syntax of the function definition is:
Syntax
snippet
function functionName( [arg1, arg2, ...argN] ){  
         //code to be executed  
}
  • Function call: We can call a function from anywhere in the program. The parameter/argument cannot differ in function calling and a function declaration. We must pass the same number of functions as it is declared in the function declaration. The syntax of the function call is:
Syntax
snippet
FunctionName();

Function Creation

We can create a function in two ways. These are:

  • Named function
  • Anonymous function
Named function

When we declare and call a function by its given name, then this type of function is known as a named function.

Syntax
functionName( [arguments] ) { }
Example
snippet
//Function Definition
function display() {
    console.log("Hello rookienerd!");
}
//Function Call
display();
TypeScript Function
Anonymous function

A function without a name is known as an anonymous function. These type of functions are dynamically declared at runtime. It is defined as an expression. We can store it in a variable, so it does not need function names. Like standard function, it also accepts inputs and returns outputs. We can invoke it by using the variable name, which contains function.

Syntax
let res = function( [arguments] ) { }
Example
snippet
// Anonymous function
let myAdd = function (x: number, y: number) : number {
    return x + y;
};
// Anonymous function call
console.log(myAdd(5,3));
TypeScript Function

Function Parameter

Parameters are the values or arguments that passed to a function. In TypeScript, the compiler accepts the same number and type of arguments as defined in the function signature. If the compiler does not match the same parameter as in the function signature, then it will give the compilation error.

Function parameter can be categories into the following:

  • Optional Parameter
  • Default Parameter
  • Rest Parameter
Optional Parameter

In JavaScript, we can call a function without passing any arguments. Hence, in a JavaScript function, the parameter is optional, and when we do this, each parameter value is undefined.

Unlike JavaScript, the TypeScript compiler will throw an error if we try to invoke a function without providing the exact number and types of parameters as declared in its function signature. To overcome this problem, we can use optional parameters by using the question mark sign ('?'). It means that the parameters which may or may not receive a value can be appended with a "?" sign to mark them as optional. In below example, e_mail_id is marked as an optional parameter.

Syntax
function function_name(parameter1[:type], parameter2[:type], parameter3 ? [:type]) { }
Example
snippet
function showDetails(id:number,name:string,e_mail_id?:string) { 
   console.log("ID:", id, " Name:",name); 
   if(e_mail_id!=undefined)  
   console.log("Email-Id:",e_mail_id); 
}
showDetails(101,"Virat Kohli");
showDetails(105,"Sachin","sachin@rookienerd.com");
TypeScript Function
Default Parameter

TypeScript provides an option to set default values to the function parameters. If the user does not pass a value to an argument, TypeScript initializes the default value for the parameter. The behavior of the default parameter is the same as an optional parameter. For the default parameter, if a value is not passed in a function call, then the default parameter must follow the required parameters in the function signature. However, if a function signature has a default parameter before a required parameter, we can still call a function which marks the default parameter is passed as an undefined value.

Note
We cannot make the parameter optional and default at the same time.
Syntax
function function_name(parameter1[:type], parameter2[:type] = default_value) { }
Example
snippet
function displayName(name: string, greeting: string = "Hello") : string {
    return greeting + ' ' + name + '!';
}
console.log(displayName('rookienerd'));   //Returns "Hello rookienerd!"
console.log(displayName('rookienerd', 'Hi'));   //Returns "Hi rookienerd!".
console.log(displayName('Sachin'));    //Returns "Hello Sachin!"
TypeScript Function
Rest Parameter

The rest parameter is used to pass zero or more values to a function. We can declare it by prefixing the three "dot" characters ('...') before the parameter. It allows the functions to have a different number of arguments without using the arguments object. The TypeScript compiler will create an array of arguments with the rest parameter so that all array methods can work with the rest parameter. The rest parameter is useful, where we have an undetermined number of parameters.

Rules to follow in rest parameter:

  • Only one rest parameter is allowed in a function.
  • It must be an array type.
  • It must be the last parameter in a parameter list.
Syntax
function function_name(parameter1[:type], parameter2[:type], ...parameter[:type]) { }
Example
snippet
function sum(a: number, ...b: number[]): number {
  let result = a;
  for (var i = 0; i < b.length; i++) {
  result += b[i];
  }
  return result;
}
let result1 = sum(3, 5);
let result2 = sum(3, 5, 7, 9);
console.log(result1 +"\n" + result2);
TypeScript Function
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +