Functions serve as the essential foundation for all applications developed in JavaScript. They enhance code readability, maintainability, and reusability. Functions enable the creation of abstraction layers, effectively simulating classes, concealing information, and organizing modules. Although TypeScript introduces classes, namespaces, and modules, functions remain a crucial component in outlining procedures. Additionally, TypeScript provides the ability to extend the standard JavaScript functions, facilitating smoother code management.
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
A function encompasses three components.
- Function declaration: This aspect informs the compiler regarding the function's name, its parameters, and the type of value it returns. The structure of the function declaration is as follows:
- Function definition: It encompasses the concrete statements that will be executed. It outlines the specifics of what task will be performed and the manner in which it will be accomplished. The syntax for defining a function is:
- Function invocation: A function may be invoked from any location within the code. The parameters/arguments must remain consistent between the function call and its declaration. It is essential to provide the same quantity of arguments as specified in the function declaration. The structure of a function call is as follows:
function functionName( [arg1, arg2, ...argN] );
function functionName( [arg1, arg2, ...argN] ){
//code to be executed
}
FunctionName();
Function Creation
There are two methods to define a function. They include:
- Named function
- Anonymous function
Named function
A function that is defined and invoked using its specified name is referred to as a named function.
Syntax
functionName( [arguments] ) { }
Example
//Function Definition
function display() {
console.log("Hello TypeScript Tutorial!");
}
//Function Call
display();
Output:
Anonymous function
A function that lacks a name is referred to as an anonymous function. These functions are created dynamically during execution. They are characterized as expressions. We can assign them to a variable, eliminating the necessity for function names. Similar to standard functions, they accept inputs and provide outputs. We can call it by utilizing the variable name that holds the function.
Syntax
let res = function( [arguments] ) { }
Example
// Anonymous function
let myAdd = function (x: number, y: number) : number {
return x + y;
};
// Anonymous function call
console.log(myAdd(5,3));
Output:
Function Parameter
Parameters refer to the values or arguments supplied to a function. In TypeScript, the compiler enforces that the number and types of arguments provided align with those specified in the function signature. If the arguments do not correspond correctly to the parameters outlined in the function signature, a compilation error will occur.
Function parameter can be categories into the following:
- Optional Parameter
- Default Parameter
- Rest Parameter
Optional Parameter
In JavaScript, it is possible to invoke a function without providing any arguments. Therefore, within a JavaScript function, the parameters are not mandatory, and when this occurs, the value of each parameter will be undefined.
In contrast to JavaScript, the TypeScript compiler generates an error when a function is called without supplying the precise number and types of arguments specified in its function signature. To address this issue, optional parameters can be implemented by employing the question mark ('?') notation. This indicates that parameters that might not have a value can be suffixed with a "?" to designate them as optional. In the example below, emailid is identified as an optional parameter.
Syntax
function function_name(parameter1[:type], parameter2[:type], parameter3 ? [:type]) { }
Example
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@logic practice.com");
Output:
Default Parameter
TypeScript offers the ability to assign default values to function parameters. When an argument is not supplied by the user, TypeScript assigns the defined default value to that parameter. The functionality of a default parameter aligns with that of an optional parameter. In the case of the default parameter, it is necessary for it to be positioned after the required parameters in the function signature if no value is provided during a function invocation. Nevertheless, if a function signature includes a default parameter preceding a required parameter, it remains possible to invoke the function while designating the default parameter 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
function displayName(name: string, greeting: string = "Hello") : string {
return greeting + ' ' + name + '!';
}
console.log(displayName('TypeScript Tutorial')); //Returns "Hello TypeScript Tutorial!"
console.log(displayName('TypeScript Tutorial', 'Hi')); //Returns "Hi TypeScript Tutorial!".
console.log(displayName('Sachin')); //Returns "Hello Sachin!"
Output:
Rest Parameter
The rest parameter enables the transmission of zero or more values to a function. It can be defined by placing three dot characters ('...') in front of the parameter. This feature permits functions to accept a variable quantity of arguments without relying on the arguments object. The TypeScript compiler generates an array of arguments for the rest parameter, ensuring compatibility with all array methods. The rest parameter proves advantageous when the number of parameters is not predetermined.
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
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);
Output: