- 4 years ago
- Afaq Arif
- 6,449 Views
-
2
In this chapter, we will discuss how to define and use functions in TypeScript closely.
Functions are the building blocks of clear, maintainable, and reusable code. A function is a set of statements to do a specific task. They organize the program into logical blocks of code. You can easily enter code after defining functions making the code to use again and again. They also make it easy to read and control the program’s code.
A function statement informs the compiler about a function’s name, return type, and parameters. A function definition gives the actual body of the function.
Sr.No | Funtions & Description |
---|
1. | A function definition states what and how a specific task would be done. |
2. | A function must be called so as to run it. |
3. | Functions may also return value along with control, back to the caller. |
4. | Parameters are a process to pass values to functions. |
Optional Parameters
When you don’t need arguments to pass to run a function then we can use optional parameters. You can set a parameter optional by adding a question mark to its name. They should be set as the last logic in a function. The syntax to announce a function with an optional parameter is given below.
function function_name (param1[:type], param2[:type], param3[:type])
Example: Optional Parameters
function disp_details(id:number,name:string,mail_id?:string) {
console.log("ID:", id);
console.log("Name",name);
if(mail_id!=undefined)
console.log("Email Id",mail_id);
}
disp_details(123,"John");
disp_details(111,"mary","[email protected]");
- The above example announces a parameterized function. The third parameter, i.e., mail_id is an optional parameter here.
- If an optional parameter doesn’t pass a value during the function call, its value will set to undefined.
- The function prints the value of mail_id only if the argument passes a value.
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
function disp_details(id, name, mail_id) {
console.log("ID:", id);
console.log("Name", name);
if (mail_id != undefined)
console.log("Email Id", mail_id);
}
disp_details(123, "John");
disp_details(111, "mary", "[email protected]");
The above code gives the following output.
Rest Parameters
Rest parameters are alike variable arguments in Java. They don’t control the number of values passed to a function. The values passed must all be of the same type. In simple, rest parameters act as placeholders for multiple arguments of the same type.
The parameter name prefixes with three periods to announce the rest parameter. Any nonrest parameter should come before the rest parameter in the program.
Example: Rest Parameters
function addNumbers(...nums:number[]) {
var i;
var sum:number = 0;
for(i = 0;i<nums.length;i++) {
sum = sum + nums[i];
}
console.log("sum of the numbers",sum)
}
addNumbers(1,2,3)
addNumbers(10,10,10,10,10)
- The function addNumbers() declaration, accepts a rest parameter nums. The data type of the rest parameter must be set to an array. The function can only have one rest parameter.
- The function can be called twice, avoiding three and six values, respectively.
- The for loop repeats through the argument list passed to the function. It calculates their sum.
It runs following JavaScript code on composing.
function addNumbers() {
var nums = [];
for (var _i = 0; _i < arguments.length; _i++) {
nums[_i - 0] = arguments[_i];
}
var i;
var sum = 0;
for (i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
console.log("sum of the numbers", sum);
}
addNumbers(1, 2, 3);
addNumbers(10, 10, 10, 10, 10);
The output of the above code is as follows.
sum of numbers 6
sum of numbers 50
Default Parameters
We can also give values by default to function parameters. They can pass values directly though.
Syntax
function function_name(param1[:type],param2[:type] = default_value) {
}
Note − You can’t declare a parameter optional and default at the same time.
Example: Default parameters
function calculate_discount(price:number,rate:number = 0.50) {
var discount = price * rate;
console.log("Discount Amount: ",discount);
}
calculate_discount(1000)
calculate_discount(1000,0.30)
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
function calculate_discount(price, rate) {
if (rate === void 0) { rate = 0.50; }
var discount = price * rate;
console.log("Discount Amount: ", discount);
}
calculate_discount(1000);
calculate_discount(1000, 0.30);
Its output is as follows.
Discount amount : 500
Discount amount : 300
- The example declares the function, calculate_discount. The function has two parameters – price and rate.
- The value of the parameter rate is set to 0.50 by default.
- The program calls the function, passing to it only the value of the parameter price. Here, the value of the rate is 0.50 (default)
- We call the same function but with two arguments. The default value of the rate is overwritten. It is set to the value that passes directly.
Anonymous Function
Anonymous functions are the functions that are not bound to their name. These functions forcefully announce at runtime. Anonymous functions can accept inputs and return outputs like standard functions do. You can not access an anonymous function after its initial creation.
Variables can be given an anonymous function. This expression is called a function expression.
Syntax
var res = function( [arguments] ) { ... }
Example ─ A Simple Anonymous function
var msg = function() {
return "hello world";
}
console.log(msg())
It runs the same code in JavaScript on composing.
It gives the following output.
Example ─ Anonymous function with parameters
var res = function(a:number,b:number) {
return a*b;
};
console.log(res(12,2))
The anonymous function returns the product of the values given to it.
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
var res = function (a, b) {
return a * b;
};
console.log(res(12, 2));
The output of the above code is as follows.
Function Expression and Function Declaration ─ Are they synonymous?
Function expression and function declaration are not the same. The function declaration is committed to its function name. It is not like a function expression.
The main difference between the two is that function declaration analyzes syntactically before their running. Nonetheless, function expressions analyze only when the script engine faces it during running.
When the JavaScript analyzer sees a function in the main code flow, it takes it as a Function Declaration. When a function comes as a part of a statement, it is a Function Expression.
The Function Constructor
TypeScript also carries defining a function with the built-in JavaScript setup called Function ().
Syntax
var res = new Function( [arguments] ) { ... }.
Example
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);
The new Function() is a call to the setup, creating and returning a function reference.
It will generate the same code in JavaScript on composing.
The output of the above example code is as follows.
Recursion and TypeScript Functions
Recursion is a process for repeating an operation by having a function call to itself again and again till it comes at a result. It is best applied when you need to call the same function often with different parameters from within a loop.
Example – Recursion
function factorial(number) {
if (number <= 0) {
return 1;
} else {
return (number * factorial(number - 1));
}
};
console.log(factorial(6)); // outputs 720
It shows the same code in JavaScript on composing.
Here is its output.
Example: Anonymous Recursive Function
(function () {
var x = "Hello!!";
console.log(x)
})() // the function invokes itself using a pair of parentheses ()
It runs the same code in JavaScript on composing.
Its output is as follows.
Lambda Functions
Lambda names to anonymous functions in programming. These functions can be used to act anonymous functions shortly. These functions are also called Arrow functions.
Lambda Function – Anatomy
There are 3 parts to a Lambda function.
- Parameters − A function may optionally have parameters
- The fat arrow notation/lambda notation (=>) − It is also called the goes to the operator
- Statements − shows the function’s instruction set
Tip − It is a convention to use a single letter parameter for a compact and precise function declaration.
Lambda Expression
It is an anonymous function expression that ends with a single line of code. Its syntax is as follows.
( [param1, parma2,…param n] )=>statement;
Example: Lambda Expression
var foo = (x:number)=>10 + x
console.log(foo(100)) //outputs 110
The program announces a lambda expression function. The function returns the sum of 10 and the argument passed.
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var foo = function (x) { return 10 + x; };
console.log(foo(100)); //outputs 110
The output of the above code is as follow.
Lambda Statement
A Lambda statement is an anonymous function declaration that points to a block of code. We use this syntax to range multiple lines. Its syntax is as follows.
( [param1, parma2,…param n] )=> {
//code block
}
Example: Lambda statement
var foo = (x:number)=> {
x = 10 + x
console.log(x)
}
foo(100)
The function’s reference is returned and stored in the variable foo.
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
var foo = function (x) {
x = 10 + x;
console.log(x);
};
foo(100);
The output of the above program is as follows.
Syntactic Variations
Parameter type Inference
We don’t need to state the data type of these parameters. You can select any data type of the parameter. We should see the following code part.
var func = (x)=> {
if(typeof x=="number") {
console.log(x+" is numeric")
} else if(typeof x=="string") {
console.log(x+" is a string")
}
}
func(12)
func("Tom")
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var func = function (x) {
if (typeof x == "number") {
console.log(x + " is numeric");
} else if (typeof x == "string") {
console.log(x + " is a string");
}
};
func(12);
func("Tom");
Its output is as follows.
12 is numeric
Tom is a string
Optional parentheses for a single parameter.
var display = x=> {
console.log("The function got "+x)
}
display(12)
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var display = function (x) {
console.log("The function got " + x);
};
display(12);
Its output is as follows.
Optional braces for a single statement, Empty parentheses for no parameter
The following example shows these two Syntactic variations.
var disp =()=> {
console.log("Function invoked");
}
disp();
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var disp = function () {
console.log("Function invoked");
};
disp();
Its output is as follows.
Function Overloads
Functions can work differently on the basis of the input given to them. In simple words, a program has many methods with the same name with different applications. This process is called Function Overloading. TypeScript provides support for function overloading.
You need to follow the steps given below to overload a function in TypeScript.
Step 1 − You need to declare multiple functions with the same name but a different function signature. Function signature consists of the following.
- The data type of the parameter
function disp(string):void;
function disp(number):void;
function disp(n1:number):void;
function disp(x:number,y:number):void;
- The sequence of parameters
function disp(n1:number,s1:string):void;
function disp(s:string,n:number):void;
Note − The function signature doesn’t include the function’s return type.
Step 2 − The declaration must follow the function definition. If the parameter types vary during overload, you can set parameter types to any. You may examine marking one or more parameters also for case b explained above as optional during the function definition.
Step 3 − Now, you can call the function to make it functional.
Example
We should take a look at the following example code.
function disp(s1:string):void;
function disp(n1:number,s1:string):void;
function disp(x:any,y?:any):void {
console.log(x);
console.log(y);
}
disp("abc")
disp(1,"xyz");
- The first two lines represent the function overload declaration. The function has two overloads.
- The function that accepts a single string parameter.
- The function accepts two values of type number and string respectively.
- The third line defines the function. The data type of the parameters is set to any. The second parameter is optional here.
- We use the last two statements to call the overloaded function.
It runs following JavaScript code on composing.
//Generated by typescript 1.8.10
function disp(x, y) {
console.log(x);
console.log(y);
}
disp("abc");
disp(1, "xyz");
The above code gives the following output.
- 4 years ago
- Afaq Arif
- 6,449 Views
-
2