Parameterized Function – Part 2

Let’s continue Part 1 of Parameterized Functions.

Recursion Functions
  • Recursion functions are those functions that call themselves repeatedly using different parameters.
  • They generally call themselves repeatedly using loops until they reach a certain break-point/result.
    Below is an example. This is a very famous example of recursion.
var n:number = 8;
console.log("Factorial of " + n + " is " + factorial(n));
function factorial(num:number){
    if(num<=0){
        return 1;
    }
    else{
        return (num * factorial(num-1));
    }
}

Below is the output of above code:

Anonymous Functions
  • These functions do not have name and cannot be reused.
  • They function as normal functions like taking parameters and returning value.
    Below is an example:
var sum=function(num1:number, num2:number){
    return (num1+num2);
}
console.log("Sum is: " + sum(10,20));

Below is the output of above code. You can also print the value inside the function as well.

Lambda Functions
  • They are like anonymous functions in TypeScript. They are called as Arrow Functions.
  • We can pass parameters in these function and also write function’s statements in this, the way we wrote for other functions.
  • The only difference is the Lambda Notation(=>).
  • We generally use a single character to declare function parameters.

Lambda Expression
It is a one liner code which acts as a function.

Syntax for Lambda Expression:

(parameter1, parameter2,..) => function statements

Below is an example:

var n2:number = 20;
var sum=(n1:number, n3:number) => n2 + n1 + n3;
console.log("Sum is: " + sum(10,30));

Below is the output of above code:

Lambda Statement
It points to a block of code.
Below is the syntax for Lambda Statement:

(parameter1, parameter2,..) => {
    function statements
}

Below is an example:

var n2:number = 20;
var add=(n1:number, n3:number) => {
    var sum = n2 + n1 + n3;
    console.log("Sum is: " + sum);
}
add(100,30);

Below is the output of above code:

Function Constructor
  • We can also define a function using JavaScript’s build in constructor called Function().
    It’s syntax:
var result = new Function(parameter1, parameter2,....)

Below is an example:

var add = new Function("num1", "num2", " return (num1 + num2)" );
var sum=add(10,20);
console.log("Sum is: " + sum);

Below is the output of above code:

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:

Functions in TypeScript

  • Functions are a set of statements that we can reuse multiple times at different places within our project.
  • Functions perform a specific task, which can be simple as well as complex.
  • Statements within a function are not executed on their own until the function is called. This process is known as function invocation.
  • We can divide our program into functions which makes the program readable and help in maintaining it.
  • We have to specify the name of the function (which follows the rules of identifier), return type and parameters (if any).

Below is the syntax of the function:

function functionName(){
   /* Function Definition
      Statements or code that will be executed 
      when this function is called */
}

For example:

function hello(){
    console.log("Inside hello function");
}
Function Invocation
hello(); //function invocation

// writing a function
function hello(){
    // function definition
    console.log("Inside hello function");
}

Below is the output of above code:

Function returning a value
  • In above examples, we are just displaying the message.
  • There can be a requirement when we want to return something from a function to use it somewhere else, say want to perform an operation and return the result.
  • The return data type can be any data type, but it should match the data type of that value that you are returning from the function.
  • Function should end with a return statement. As soon as the control of the function encounters a return statement, it will execute that return statement and the control goes back to the statement from the function was initially invoked. It will not execute the statements after that return.
  • There can only be one return value, however there can be multiple return statements. For example, if there is a statement with if…else statement, we can put return statement in both if and else.
  • We can invoke a function from another function.
    Below is the syntax:
function functionName():returnDataType{
    // Statements
       return value;
}

In below example, we are defining two functions, hello (which does not return a value) and add (which returns the sum of two numbers). add() function in invoked from another function, hello().

hello(); //function invocation

// writing a function
function hello(){
    // function definition
    console.log("Inside hello function");
    var sum=add(); //another function is called from a function
    console.log("Sum is: " + sum);
}

function add():number{
    var num1:number=10;
    var num2:number=20;
    return (num1+num2);
}

Below is the output of above code:

Loops in TypeScript

Loops are used to execute certain set of statements n number of times.

There are three types of loops in TypeScript: for loop, while loop and do-while loop.

for loop

for loop is used when we know the number of times we want to execute a set of statements.
Below is a sample code:

var i:number;
for(i=1; i<=10; i++){
    console.log(i);
}

Below is the output of above code:

while loop

while loop is used when we are not sure how many number of times we want to execute a set of statements.
Below is a sample code:

var num:number=30;
while(num>0 && num%3==0){
    console.log(num/3);
    num-=3;
}

Below is the output of above code:

do-while loop

do-while loop is just like while loop. The only difference is if the condition is false, while loop will not be executed even once, do-while will be executed at least once.
Below is a sample code:

var num:number=30;
do{
    console.log("Do-While loop will be executed at least once even if the condition is false!");
}while(num>40)

Below is the output of above code:

Conditional Statements in TypeScript – switch

Conditional Statements are used to make decisions in the code and execute a set of statements accordingly. If a condition is true, one set of statements is executed. If the condition is false, no or another set of statements is executed.

There are two types of conditional statements: if and switch. In this article, we will discuss about switch statement.

Basic Syntax of switch statement is:

switch(variable) { 
   case constant1: { 
      //statements; 
      break; //breaks the flow of the execution
   } 
   case constant2: { 
      //statements; 
      break; 
   } 
   default: { //optional
      //statements; 
      break; 
   } 
} 
  • We test the cases against a defined value. Whichever case matches the value, that case is executed.
  • We put break statement to stop the execution of code after that case.
  • default is used when the defined value does not matches any case. This is optional.
  • There can be any number of cases in switch statements.
  • Cases should have unique constants to match the variable of Switch.
  • Data Type of Switch variable and case constant should be same.
  • Case contacts should only be constants. They should not be expressions or variable.

Below is an example when the defined value matched one of the case.

var weeknum:number = 4;
switch(weeknum){
    case 1:
        console.log("Sunday");
        break;
    case 2:
        console.log("Monday");
        break;
    case 3:
        console.log("Tuesday");
        break;
    case 4:
        console.log("Wednesday");
        break;
    case 5:
        console.log("Thursday");
        break;
    case 6:
        console.log("Friday");
        break;
    case 7:
        console.log("Saturday");
        break;
    default:
        console.log("Invalid Value");

}

Below is the output of above code.

Below is an example for default statement.

var weeknum:number = 9;
switch(weeknum){
    case 1:
        console.log("Sunday");
        break;
    case 2:
        console.log("Monday");
        break;
    case 3:
        console.log("Tuesday");
        break;
    case 4:
        console.log("Wednesday");
        break;
    case 5:
        console.log("Thursday");
        break;
    case 6:
        console.log("Friday");
        break;
    case 7:
        console.log("Saturday");
        break;
    default:
        console.log("Invalid Value");

}

Below is the output of above code:

 

Conditional Statements in TypeScript – if…else

Conditional Statements are used to make decisions in the code and execute a set of statements accordingly. If a condition is true, one set of statements is executed. If the condition is false, no or another set of statements is executed.

There are two types of conditional statements: if and switch. In this article, we will be discussing various forms of if-statements.

if statement

Only if statement is included with a condition. If the result of this condition is true, a set of statements is executed. No else condition is present.
Below is an example when if condition returns false.

var num1:number = 100;
if(num1>200){
console.log("Inside if statement");
}
console.log("Outside if statement");

Below is the output of above code:

Below is an example when if condition returns true.

var num1:number = 100;
if(num1<200){
console.log("Inside if statement");
}
console.log("Outside if statement");

Below is the output of above code:

if…else statement

Here, when the condition is true, if block is executed. When the condition is false, else block is executed.
Below is the example when condition is true and if block is executed.

var num1:number = 100;
if(num1<200){
    console.log("Inside if, as condition is true");
}
else{   
    console.log("Inside else, as condition is false");
}

Below is the output of above code:

Below is the example when condition is false and else block is executed.

var num1:number = 100;
if(num1>200){
    console.log("Inside if, as condition is true");
}
else{   
    console.log("Inside else, as condition is false");
}

Below is the output of above code:

if…else if..else Statement

Below are some sample codes:

var num1:number = 100;
var num2:number = 200;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Another Example:

var num1:number = 100;
var num2:number = 100;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Nested If

We can nest if statements inside another if or else block. Below is an example related to this:

var num1:number = 100;
var num2:number = 200;
var num3:number = 100;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
    if(num1 == num3){
        console.log(num1 + " is equal to " + num3);
    }
    else{
        console.log(num1 + " is not equal to " + num3);
    }
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Operators in TypeScript

We perform a function on a piece of data using operators. This piece of data on which a function is performed is called operand(s).

There are various operators divided into multiple categories:

Arithmetic Operators

Arithmetic operators are used to perform operations on numerical operands. Below are some arithmetic operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
+ Addition. This will return the sum of two operands a + b = 30
Subtraction. This will return the difference between two operands b-a=10
* Multiplication. This will return the product of two operands a*b=200
/ Division. This will return quotient b/a=2
% Modulus. This will return remainder b%a=0
++ Increment. This will increment the value of operand by one a++ will return 11
Decrement. This will decrement the value of operand by one a– will return 9
Relational Operators

These operators define the relationship between two operands and returns true or false. Below are some relational operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
> Greater Than (b > a) will return true
< Less Than (a < b) will return true
>= Greater than or equal to (a >= b) will return false
<= Less than or equal to (a <= b) will return true
== Equal To (a == b) will return false
!= Not Equal to (a != b) will return true
Logical Operators

These operators are used to combine two or more conditions. They also return boolean value, true or false. Below are some logical operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
&& AND. This will return true if all the conditions are true ((a < b) && (a != b)) will return true as both these conditions are true
|| OR. This will return true if any one of the condition is true ((a < b) && (a == b)) will return true as first condition is true
! NOT. This will return the opposite of the condition result (!(a < b)) will return false.
Assignment Operators

These operators are used to assign values to a variable. Below are some assignment operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
= Assignment. Assigns the value of right side operand to left side operand b = a (This will assign 10 to variable b)
+= Add and Assign. Add value of right operand to left operand and then assigns the sum to left operand a += b (Adds 20 to 10 and then assigns sum(30) to variable a)
-= Subtract and Assign. Subtract right operand from left operand and then assigns the difference to left operand b -= a (Subtracts 10 from 20 and assigns the difference(10) to variable b)
*= Multiply and Assign. Multiply right operand to left operand then assigns the product to left operand. a *= b (Multiplies a and b and assigns the product(200) to a)
/= Divide and Assign. Divides left operand with right operand and assigns quotient to left operand b /= a (Divides b by a and assigns quotient(2) to b)
Negation Operator (-)

It will change the sign of the integer value. That is, it will change positive value to negative value and negative value to positive value.

var num1:number = 10;
var num2 = -num1;
console.log("num1: " + num1 + "; num2: " + num2);
Output: num1: 10; num2: -10

After executing, num1 will be 10 and num2 will be -10.

Concatenation Operator (+)

This operator is applied on string values to concatenate two strings together. We can concatenate multiple strings in one sentence using multiple concatenation operators between two strings.

var fullName:string="Hello" + " Akanksha" + " Garg";
console.log(fullName);
Output: Hello Akanksha Garg

Kindly note that concatenation operator does not add a space between two strings, you have to explicitly place a space like I did in my example.

typeof Operator

This operator returns the data type of a variable.

var firstname="Akanksha";
console.log(typeof(firstname));
Output: string

Variables in TypeScript

    • Variable is a named space in memory that stores a value.
    • Variables can include characters or digits or both. But they cannot begin with digits.
    • They cannot contain special symbols except underscore(_) or dollar sign($).
    • We cannot use keywords as variables and they must be unique within a scope.
    • They are case-sensitive and cannot contain spaces.
    • Some examples of Identifiers are: firstName, last_Name, number1 etc.
    • You should declare a variable using a data type before you use it.
    • Use var keyword to declare a variable.
    • For example: var value:string=”Hello”;
var value:string=”Hello”; Declaring a variable of a particular data type and storing a value in it.
var value:string; Declaring a variable of a particular data type. As we are not assigning a value to it, by default undefined is assigned to it
var value=”Hello”; Declaring a variable and storing a value in it. Data type of the variable is determined by the type of value stored in it. Hence it will be of string type
var value; Declaring a variable. As nothing is specified, the data type will be any and value will be undefined

Data Types in TypeScript

Data Types represent different types of values supported by a language. This will check if a value is valid or not before assigning it to a variable. This ensures the behavior of the code.

Any Type

The any data type is the super data type of all the data types in TypeScript. It denotes a dynamic type. We can assign any type of value in this type of variable. We use this data type when we want to opt out of type checking for a variable.

Built-In Data Types

Data Type Keyword Description
Number number It can be both integer and fraction value
String string Unicode character values
Boolean boolean logical values, true or false
Void void used as functions return types when we do not want to return anything
Null null leave the variable blank and not assign any value to it
Undefined undefined denotes value given to all uninitialized variables.

There is a difference between null and undefined. They cannot only be used to assign values to the variables. A variable initialized with undefined means that the variable has no value or object assigned to it while null means that the variable has been set to an object whose value is undefined.

User-Defined Data Types

These includes Enums, classes, interfaces, arrays and tuples.

Keywords in TypeScript

We cannot use keywords as identifier names.

Below is a list of few keywords in TypeScript:

break case var module
public null in finally
any new package continue
as type if number
private super for return
do try implement extends
switch typeof get else
export void new false
function let const catch
break case var yield
interface static true this
while enum instanceof string
throw any
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