Parameterized Function – Part 1

We have already seen what are functions in TypeScript. Let’s see what are parameterized functions.
This is Part 1 of Parameterized Function’s section. Part 2 is in another post.

It is not necessary to mention the data type of the parameters. If you do not mention the data type, it will take any as their data type. Below is an example of a parameterized function which takes two numbers as parameters, adds them and returns the sum of those two numbers.

var num1:number=10;
var num2:number=20;
hello();
function hello(){
console.log("Hellozz");
var sum=add(num1,num2);
console.log(num1 + " + " + num2 + " = " + sum);
}
function add(n1:number, n2:number):number{
return (n1+n2);
}

Below is the output of above code:

Optional Parameters

Optional Parameters are not compulsory to pass at the time of function invocation. They are marked by a question mark and should be declared at the end of the parameter list.
Below is an example of optional parameters:

var num1:number=10;
var num2:number=20;
var num3:number=40; 
hello();
function hello(){
    console.log("Hellozz");
    var sum=add(num1,num2);
    console.log(num1 + " + " + num2 + " = " + sum);
    var sum1=add(10,20,30);
    console.log(num1 + " + " + num2 + " + " + num3 + " = " + sum1 );
}
function add(n1:number, n2:number, n3?:number):number{
    if(n3==undefined){
        return (n1+n2);
    }
    else if(n3!=undefined){
        return(n1+n2+n3);
    }

}

Below is the output of above code:

Rest Parameters

We can pass multiple parameters to a function using rest parameters, but they should of the same type. To declare a rest parameter, parameter name is prefixed with three dots.
Below is an example of rest parameters:

hello();
function hello(){
    console.log("Hellozz");
    console.log(add(10,10,10,10));
    console.log(add(100,200));
}
function add(...values:number[]):number{
    var i:number;
    var sum:number=0;
    for(i=0; i<values.length;i++){
        sum+=values[i];
    }
    return sum;
}

Below is the output of above code:

Default Parameters

Sometimes we assign a default value to parameters, until explicitly specified. That is, if you do not pass any value to that parameter, it will automatically take the default value.
Below is an example:

empDetails("Akanksha");
empDetails("Aarav","HR");

function empDetails(name:string, department:string="IT"){
    console.log("Employee Name: " + name + "; Department: " + department);
}

Below is the output of above code:

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started