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 as 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;
}

Below is an example. Here, 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

There is another conditional statement that we use use in TypeScript. That is Switch Case 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

Variable Scope in TypeScript

Variable Scope defines where the variable is defined and the area in which we can use the variable.

Variables are divided in three Scopes:

Global Scope
  • Global variables are declared outside all the functions and classes.
  • Generally we declare global variables at the starting of our program.
  • They can be accessed from anywhere within the code.
Class Scope
  • These variables are also called as fields.
  • These variables are declared within a class but outside any method.
  • They accessed by using the object of the class.
  • If these variables are declared static, then we do not have to create an object to access them. We can simply access them using class name.
Local Scope
  • These variables are declared within a method, loop etc. and they can be accessed within them only.
  • For example, if a variable is declared within a method, it can be access from within that method only. We cannot access it from outside that method.

Below is the example for various variable scopes:

var globalVar = 100;
class Values{
    classvar=200;
    static staticVar=50;

    localMethod():void{
        var localVar=300;
        console.log("Local Variable: " + localVar);
    }
}
var obj=new Values();
console.log("Global Variable:" + globalVar);
console.log("Class Variable: " + obj.classvar);
console.log("Static Variable: " + Values.staticVar);
obj.localMethod();

Below is the JavaScript conversion of the above code:

var globalVar = 100;
var Values = /** @class */ (function () {
    function Values() {
        this.classvar = 200;
    }
    Values.prototype.localMethod = function () {
        var localVar = 300;
        console.log("Local Variable: " + localVar);
    };
    Values.staticVar = 50;
    return Values;
}());
var obj = new Values();
console.log("Global Variable:" + globalVar);
console.log("Class Variable: " + obj.classvar);
console.log("Static Variable: " + Values.staticVar);
obj.localMethod();

Below is the output of above code using NodeJS Command prompt:

If you try to access a variable outside of its scope, it will give a compilation error:
Could not find symbol ‘localvar’

Related Articles
Compilation and Execution of TypeScript Code

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

Sample program using TypeScript

Before going further, look here for some basic concepts of TypeScript.

Below is a sample program using TypeScript. Save this program with, say HelloWorld.ts

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

When compiled, this code will be converted to JavaScript and a new file is created in the same folder with the same name, but with .js extension (HelloWorld.js)

   
var value = "Hello World!!";
console.log(value);

Open NodeJS Command Prompt.
Go to the folder where you have saved your TypeScript file.
Write tsc HelloWorld.ts
Above code will compile your code in .js file.

Then Write node HelloWorld.js
Above code will execute .js file and displays the result. Remember to use .js as extension.

Design a site like this with WordPress.com
Get started