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.
These are the main advantages of functions.
There are three aspects of a function.
function functionName( [arg1, arg2, ...argN] );
function functionName( [arg1, arg2, ...argN] ){ //code to be executed }
FunctionName();
We can create a function in two ways. These are:
When we declare and call a function by its given name, then this type of function is known as a named function.
functionName( [arguments] ) { }
//Function Definition function display() { console.log("Hello rookienerd!"); } //Function Call display();
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.
let res = function( [arguments] ) { }
// Anonymous function let myAdd = function (x: number, y: number) : number { return x + y; }; // Anonymous function call console.log(myAdd(5,3));
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:
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.
function function_name(parameter1[:type], parameter2[:type], parameter3 ? [:type]) { }
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 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.
function function_name(parameter1[:type], parameter2[:type] = default_value) { }
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!"
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:
function function_name(parameter1[:type], parameter2[:type], ...parameter[:type]) { }
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);