TypeScript Functions
A function is a set of statements that together perform a task.
You can divide your code into different functions. How you divide your code into different functions is up to you, but logically, the division is usually based on each function performing a specific task.
A function declaration tells the compiler about the function's name, return type, and parameters. A function definition provides the actual body of the function.
Function Definition
A function is a block of code wrapped in curly braces, preceded by the keyword function
:
The syntax is as follows:
function function_name() {
// code to be executed
}
Example
TypeScript
function () {
// function definition
console.log("Function called")
}
Calling a Function
A function can only execute the code inside it by being called.
The syntax is as follows:
function_name()
Example
TypeScript
function test() { // function definition
console.log("Function called")
}
test() // call the function
Function Return Value
Sometimes, we want the function to return the result to the place where it was called.
This can be achieved by using the return
statement.
When using the return
statement, the function stops executing and returns the specified value.
The syntax is as follows:
function function_name(): return_type {
// statements
return value;
}
return_type
is the type of the return value.- The
return
keyword is followed by the value to be returned. - Typically, a function has only one
return
statement. - The return type must match the return type defined in the function.
Example
TypeScript
// function definition
function greet(): string { // returns a string
return "Hello World"
}
function caller() {
var msg = greet() // call greet() function
console.log(msg)
}
// call the function
caller()
- The example defines the function
greet()
, which returns a string. - The
greet()
function returns a value to the caller, which is the variablemsg
, and then outputs this return value.
Compiling the above code yields the following JavaScript code:
JavaScript
// function definition
function greet() {
return "Hello World";
}
function caller() {
var msg = greet(); // call greet() function
console.log(msg);
}
// call the function
caller();
Functions with Parameters
When calling a function, you can pass values to it, which are called parameters.
These parameters can be used within the function.
You can send multiple parameters to a function, separated by commas ,
:
The syntax is as follows:
function func_name(param1 [:datatype], param2 [:datatype]) {
}
param1
,param2
are parameter names.datatype
is the parameter type.
Example
TypeScript
function add(x: number, y: number): number {
return x + y;
}
console.log(add(1, 2))
- The example defines the function
add()
, which returns a number. - The
add()
function defines two parameters of type number, adds them together, and returns the result.
Compiling the above code yields the following JavaScript code:
JavaScript
function add(x, y) {
return x + y;
}
console.log(add(1, 2));
The output is:
3
Optional and Default Parameters
Optional Parameters
In TypeScript functions, if we define parameters, we must pass these parameters unless they are set as optional. Optional parameters are indicated by a question mark ?
.
Example
TypeScript
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // Error, missing parameter
let result2 = buildName("Bob", "Adams", "Sr."); // Error, too many parameters
let result3 = buildName("Bob", "Adams"); // Correct
The following example sets lastName
as an optional parameter:
TypeScript
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // Correct
let result2 = buildName("Bob", "Adams", "Sr."); // Error, too many parameters
let result3 = buildName("Bob", "Adams"); // Correct
Optional parameters must follow required parameters. If we want firstName
to be optional and lastName
to be required, we need to adjust their positions.
If all parameters are optional, it doesn't matter.
Default Parameters
We can also set default values for parameters. If a value for the parameter is not passed when calling the function, the default value is used. The syntax is:
function function_name(param1[:type], param2[:type] = default_value) {
}
Note: A parameter cannot be both optional and have a default value.
Example
In the following example, the parameter rate
is set to a default value of 0.50. If no value is passed, this default value is used:
TypeScript
function calculate_discount(price: number, rate: number = 0.50) {
var discount = price * rate;
console.log("Calculated result: ", discount);
}
calculate_discount(1000)
calculate_discount(1000, 0.30)
Compiling the above code yields the following JavaScript code:
JavaScript
function calculate_discount(price, rate) {
if (rate === void 0) { rate = 0.50; }
var discount = price * rate;
console.log("Calculated result: ", discount);
}
calculate_discount(1000);
calculate_discount(1000, 0.30);
The output is:
Calculated result: 500
Calculated result: 300
Rest Parameters
There are cases where we don't know how many parameters to pass to a function. In such cases, we can use rest parameters.
The rest parameter syntax allows us to pass an indefinite number of arguments as an array.
TypeScript
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
The last named parameter restOfName
is prefixed with ...
, making it an array of the remaining parameters, indexed from 0 (inclusive) to restOfName.length
(exclusive).
TypeScript
function addNumbers(...nums: number[]) {
var i;
var sum: number = 0;
for (i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
console.log("Sum is: ", sum)
}
addNumbers(1, 2, 3)
addNumbers(10, 10, 10, 10, 10)
Compiling the above code yields the following JavaScript code:
JavaScript
function addNumbers() {
var nums = [];
for (var _i = 0; _i < arguments.length; _i++) {
nums[_i] = arguments[_i];
}
var i;
var sum = 0;
for (i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
console.log("Sum is: ", sum);
}
addNumbers(1, 2, 3);
addNumbers(10, 10, 10, 10, 10);
The output is:
Sum is: 6
Sum is: 50
Anonymous Functions
An anonymous function is a function without a name.
Anonymous functions are declared dynamically at runtime, and apart from lacking a function name, they are similar to standard functions.
We can assign an anonymous function to a variable, making the expression a function expression.
The syntax is as follows:
var res = function( [arguments] ) { ... }
Example
Anonymous function without parameters:
TypeScript
var msg = function() {
return "hello world";
}
console.log(msg())
Compiling the above code yields the following JavaScript code:
JavaScript
var msg = function () {
return "hello world";
};
console.log(msg());
The output is:
hello world
Anonymous function with parameters:
TypeScript
var res = function(a: number, b: number) {
return a * b;
};
console.log(res(12, 2))
Compiling the above code yields the following JavaScript code:
JavaScript
var res = function (a, b) {
return a * b;
};
console.log(res(12, 2));
The output is:
24
Self-Invoking Anonymous Functions
TypeScript
(function () {
var x = "Hello!!";
console.log(x)
})();
Compiling the above code yields the following JavaScript code:
JavaScript
(function () {
var x = "Hello!!";
console.log(x)
})();
The output is:
Hello!!
(function () {
var x = "Hello!!";
console.log(x)
})()
Output result:
Hello!!
Constructor Functions
TypeScript also supports defining functions using JavaScript's built-in constructor function Function():
Syntax format:
var res = new Function ([arg1[, arg2[, ...argN]],] functionBody)
Parameter explanation:
- arg1, arg2, ... argN: Parameter list.
- functionBody: A string containing JavaScript statements that define the function.
Example
TypeScript
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);
Compiling the above code yields the following JavaScript code:
JavaScript
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);
Output result:
12
Recursive Functions
Example:
Example
TypeScript
function factorial(number) {
if (number <= 0) { // Stop execution
return 1;
} else {
return (number * factorial(number - 1)); // Call itself
}
};
console.log(factorial(6)); // Output 720
Compiling the above code yields the following JavaScript code:
JavaScript
function factorial(number) {
if (number <= 0) { // Stop execution
return 1;
}
else {
return (number * factorial(number - 1)); // Call itself
}
}
;
console.log(factorial(6)); // Output 720
Output result:
720
Lambda Functions
Lambda functions are also known as arrow functions.
Arrow function expressions have a shorter syntax than function expressions.
Function with a single statement:
( [param1, parma2,…param n] )=>statement;
Example
TypeScript
var foo = (x:number)=>10 + x
console.log(foo(100)) // Output result is 110
Compiling the above code yields the following JavaScript code:
JavaScript
var foo = function (x) { return 10 + x; };
console.log(foo(100)); // Output result is 110
Output result:
110
Function with a block of statements:
( [param1, parma2,…param n] )=> {
// Code block
}
Example
The following example declares a lambda expression function that returns the sum of two numbers:
TypeScript
var foo = (x:number)=> {
x = 10 + x
console.log(x)
}
foo(100)
Compiling the above code yields the following JavaScript code:
JavaScript
var foo = function (x) {
x = 10 + x;
console.log(x);
};
foo(100);
Output result:
110
TypeScript
var func = (x)=> {
if(typeof x=="number") {
console.log(x+" is a number")
} else if(typeof x=="string") {
console.log(x+" is a string")
}
}
func(12)
func("Tom")
Compiling the above code yields the following JavaScript code:
JavaScript
var func = function (x) {
if (typeof x == "number") {
console.log(x + " is a number");
}
else if (typeof x == "string") {
console.log(x + " is a string");
}
};
func(12);
func("Tom");
Output result:
12 is a number
Tom is a string
Single parameter ()
is optional:
TypeScript
var display = x => {
console.log("Output is "+x)
}
display(12)
Compiling the above code yields the following JavaScript code:
JavaScript
var display = function (x) {
console.log("Output is " + x);
};
display(12);
Output result:
Output is 12
Empty parentheses for no parameters:
TypeScript
var disp =()=> {
console.log("Function invoked");
}
disp();
Compiling the above code yields the following JavaScript code:
JavaScript
var disp = function () {
console.log("Function invoked");
};
disp();
Output result:
Function invoked
Function Overloading
Overloading is having the same method name with different parameters and return types.
Each overloaded method (or constructor) must have a unique parameter type list.
Different parameter types:
function disp(string):void;
function disp(number):void;
Different parameter counts:
function disp(n1:number):void;
function disp(x:number,y:number):void;
Different parameter type order:
function disp(n1:number,s1:string):void;
function disp(s:string,n:number):void;
If parameter types differ, set them to any.
For different parameter counts, make parameters optional.
Example
The following example defines different parameter types and counts:
TypeScript
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");
Compiling the above code yields the following JavaScript code:
JavaScript
function disp(x, y) {
console.log(x);
console.log(y);
}
disp("abc");
disp(1, "xyz");
Output result:
abc
undefined
1
xyz