TypeScript tutorial: Lesson 6 – Functions


TypeScript – Functions

Defining a Function

Syntax:

function [function_name]() { 
   //body 
}

Example 1:

function sum(x:number,y:number):number { 
   return x+y
} 

Example 2: anonymous function

function (x:number,y:number):number { 
   return x+y
}

Calling a Function

A function must be called so as to execute it. This process is termed as function invocation.

Syntax

function_name()

Note: function_name can be a variable

Example 1:

function sum(x:number,y:number):number { 
   return x+y
}

console.log(sum(1,2))

Example 2: anonymous function

(function (x:number,y:number):number { 
   return x+y
})(1,2)

Example 3:

var sum = function (x:number,y:number):number { 
   console.log( x+y )
}

sum(1,2)

Returning a Function

Functions may also return value along with control, back to the caller. Such functions are called as returning functions.

Syntax

function [function_name]():return_type { 
   //body 
   return value; 
}

Note: return_type must one of these values: string, number, object, boolean, void, any

Example:

var round = function (x:number):any { 
   return function(){ 
      return Math.round(x)
   }
}

console.log(round(2.2)())

Function Parameters

While calling a function, there are two ways that arguments can be passed to a function

S.No. Call Type & Description
1.

Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2.

Call by pointer

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter

Syntax:

function [func_name](param1[:datatype1], [param2[?][:datatype2]]) {   
    //body
}

Call by pointer
Example:

var myInfo = {
   name: 'Tutorialspots',
   age: 35
}

function changeAge(info:any,newAge:number){
   info.age = newAge
}

changeAge(myInfo,40)

console.log(myInfo)

Result:

[LOG]: { "name": "Tutorialspots", "age": 40 } 

Optional Parameters

The optional parameter should be set as the last argument in a function:
Example: Optional Parameters

function sum(x:number,y:number,z?:number) { 
   console.log("x:", x)
   console.log("y:", y)
   
   if(typeof z!="undefined")  
   console.log("z:",z)

   return x+y+(typeof z!="undefined"?z:0)
}

console.log(sum(1,2,3))
console.log(sum(1,2))

Result:

[LOG]: x:,  1 
[LOG]: y:,  2 
[LOG]: z:,  3 
[LOG]: 6 
[LOG]: x:,  1 
[LOG]: y:,  2 
[LOG]: 3 

Rest Parameters

Detail: TypeScript tutorial: Lesson 3 Go to: Rest Operator (Rest parameters)

Default Parameters

Like PHP, TypeScript function parameters can also be assigned values by default:

Syntax:

function [function_name](param1[:type1], param2[:type2] = default_value) { 
    //body
}

Example:

var myInfo = {
   name: 'Tutorialspots',
   age: 35
}

function changeAge(newAge:number=40){
   myInfo.age = newAge
}

changeAge()

console.log(myInfo)

Result:

[LOG]: { "name": "Tutorialspots", "age": 40 } 

The Function Constructor

Like PHP (function create_function), TypeScript also supports defining a function with the built-in JavaScript constructor called Function().

Syntax

new Function( [arguments,] function_body_as_string )

Example:

var sum = new Function("x","y","return x+y")

console.log(sum(1,2))

Result:

[LOG]: 3

Lambda Functions
Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.

Lambda Expression
Syntax:

( [param1, param2, …param n] )=>statement

Example 1:

var myFunc = (x:number,y:number)=>(x=x+1,x+y)

console.log(myFunc(1,2))

Result:

[LOG]: 4 

Lambda Statement
Syntax:

( [param1, param2, …param n] )=>{
    //block
}

Example 2:

var myFunc = (x:number,y:number)=>{
   x=x+1
   console.log(x+y)
}

myFunc(1,2)

Result:

[LOG]: 4 

Generator function
function*
The function* keyword defines a generator function expression.
yield
Pause and resume a generator function.
yield*
Delegate to another generator function or iterable object.

The Generator object: is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Constructor: you must use generator function:

Example:

function* foo() {
    yield 2
    yield 1
}

const iterator = foo()

Instance methods
Generator.prototype.next()
Returns a value yielded by the yield expression.
Generator.prototype.return()
Returns the given value and finishes the generator.
Generator.prototype.throw()
Throws an error to a generator (also finishes the generator, unless caught from within that generator).

Example:

function* foo() {
    yield 2
    yield 1
}

const iterator = foo()

console.log(iterator.next().value)
console.log(iterator.next().value)

Result:

[LOG]: 2 
[LOG]: 1 

Example: yield* keyword

function* func1() {
  yield 100
  yield 101
}

function* func2() {
  yield 99 
  yield* func1()
}

const iterator = func2()

console.log(iterator.next().value)
console.log(iterator.next().value)
console.log(iterator.next().value)

Result:

[LOG]: 99 
[LOG]: 100 
[LOG]: 101 

Function Overloads

Functions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is called as Function Overloading. TypeScript provides support for function overloading.

Example:

//Declare multiple functions with the same name but different function signature
function calculateDistance(p1:object,p2:object):number
function calculateDistance(x1:number,y1:number,x2:number,y2:number):number

//Function definition with optional parameters
function calculateDistance(a:any,b:any,c?:any,d?:any):number{
   if(typeof a == "number"){
      return Math.sqrt((a-c)**2 + (b-d)**2)
   }else{
      return Math.sqrt((a.x-b.x)**2+(a.y-b.y)**2)
   }
}

console.log(calculateDistance({x:10,y:20},{x:30,y:50}))
console.log(calculateDistance(10,20,30,50))

Result:

[LOG]: 36.05551275463989 
[LOG]: 36.05551275463989 

Leave a Reply