Ts Function
Functions are statements that execute together as a group to perform a task.
You can divide your code into different functions. How you divide 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 a function's name, return type, and parameters. The function definition provides the actual body of the function.
* * *
## Function Definition
A function is a block of code designed to perform a particular task, and it is executed when "something" invokes it (calls it).
The syntax is as follows:
function function_name(){ // code to be executed}
### Example
## TypeScript
function(){console.log("Function called")}
* * *
## Calling a Function
A function can be invoked (called) after it has been declared.
The syntax is as follows:
function_name()
### Example
## TypeScript
function test(){console.log("Function called")}test()
* * *
## Function Return Value
Sometimes, we want a function to return a value to the place where it was called.
This can be achieved by using the `return` statement.
When a `return` statement is executed, 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 data type of the value the function returns.
* The `return` keyword is followed by the value to be returned.
* Generally, a function has only one `return` statement.
* The type of the returned value must match the return type (`return_type`) defined in the function declaration.
### Example
## TypeScript
function greet():string{return"Hello World"}function caller(){var msg = greet()console.log(msg)}caller()
* In this example, the function _greet()_ is defined to return a value of type `string`.
* The _greet()_ function returns the value "Hello World" to the caller via the `return` statement, which is then stored in the variable `msg` and logged to the console.
Compiling the above code produces the following JavaScript code:
## JavaScript
function greet(){return"Hello World"; }function caller(){var msg = greet(); console.log(msg); }caller();
* * *
## Function with Parameters
When you call a function, you can pass values to it. These values are called parameters.
These parameters can be used inside 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 the parameter names.
* `datatype` is the data type of the parameters.
### Example
## TypeScript
function add(x: number, y: number): number{return x + y; }console.log(add(1,2))
* In this example, the function _add()_ is defined to return a value of type `number`.
* The _add()_ function takes two parameters of type `number`, adds them together, and returns the result.
Compiling the above code produces 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 a parameter, we must pass a value for it unless we mark it as optional. Optional parameters are denoted by a question mark `?`.
**Example**
## TypeScript
function buildName(firstName: string, lastName: string){return firstName + "" + lastName; }let result1 = buildName("Bob"); let result2 = buildName("Bob", "Adams", "Sr."); let result3 = buildName("Bob", "Adams");
In the following example, we set `lastName` as an optional parameter:
## TypeScript
function buildName(firstName: string, lastName?: string){if(lastName)return firstName + "" + lastName; else return firstName; }let result1 = buildName("Bob"); let result2 = buildName("Bob", "Adams", "Sr."); let result3 = buildName("Bob", "Adams");
Optional parameters must come after required parameters. If we wanted `firstName` to be optional and `lastName` to be required in the above example, we would need to swap their positions, placing `firstName` after `lastName`.
If both parameters are optional, the order doesn't matter.
### Default Parameters
We can also set default values for parameters. If a value for that parameter is not provided when the function is called, 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 function parameter `rate` is set to a default value of 0.50. If no value is passed for this parameter when the function is called, the default value is used:
## TypeScript
function calculate_discount(price:number,rate:number = 0.50){var discount = price * rate; console.log("Calculation result: ",discount); }calculate_discount(1000)calculate_discount(1000,0.30)
Compiling the above code produces the following JavaScript code:
## JavaScript
function calculate_discount(price, rate){if(rate === void 0){rate = 0.50; }var discount = price * rate; console.log("Calculation result: ", discount); }calculate_discount(1000); calculate_discount(1000, 0.30);
The output is:
Calculation result: 500Calculation result: 300
* * *
## Rest Parameters
There are situations where we don't know how many parameters will be passed to a function. In such cases, we can use rest parameters.
Rest parameter syntax allows us to represent 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 of the function, `restOfName`, is prefixed with `...`. It becomes an array containing the rest of the parameters, with index values 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; }console.log("Sum is: ",sum)}addNumbers(1,2,3)addNumbers(10,10,10,10,10)
Compiling the above code produces the following JavaScript code:
## JavaScript
function addNumbers(){var nums = []; for(var _i = 0; _i<arguments.length; _i++){nums = arguments; }var i; var sum = 0; for(i = 0; i For example:
>
> Once upon a time, there was a mountain. On the mountain was a temple. In the temple, an old monk was telling a story to a young monk! What was the story? "Once upon a time, there was a mountain. On the mountain was a temple. In the temple, an old monk was telling a story to a young monk! What was the story? 'Once upon a time, there was a mountain. On the mountain was a temple. In the temple, an old monk was telling a story to a young monk! What was the story?β¦β¦'"
### Example
## TypeScript
function factorial(number){if(number<= 0){return 1; }else{return(number * factorial(number - 1)); }}; console.log(factorial(6));
Compiling the above code produces the following JavaScript code:
## JavaScript
function factorial(number){if(numberstatement;
### Example
The following example declares a lambda expression function that returns the sum of two numbers:
## TypeScript
var foo = (x:number)=>10 + x console.log(foo(100))
Compiling the above code produces the following JavaScript code:
## JavaScript
var foo = function(x){return 10 + x; }; console.log(foo(100));
The output is:
110
For a function with a statement block:
( [param1, param2,β¦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 produces the following JavaScript code:
## JavaScript
var foo = function(x){x = 10 + x; console.log(x); }; foo(100);
The output is:
110 We can omit the parameter types and infer them from the function body:
## 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 produces 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");
The output is:
12 is a numberTom is a string
Parentheses `()` are optional for a single parameter:
## TypeScript
var display = x =>{console.log("Output is "+x)}display(12)
Compiling the above code produces the following JavaScript code:
## JavaScript
var display = function(x){console.log("Output is " + x); }; display(12);
The output is:
Output is 12
For no parameters, empty parentheses can be used:
## TypeScript
var disp =()=>{console.log("Function invoked"); }disp();
Compiling the above code produces the following JavaScript code:
## JavaScript
var disp = function(){console.log("Function invoked"); }; disp();
The output is:
Function invoked
* * *
## Function Overloading
Overloading means having multiple functions with the same name but different parameters. The return types can be the same or different.
Each overloaded function (or constructor) must have a unique parameter type list.
Different parameter types:
function disp(string):void; function disp(number):void;
Different number of parameters:
function disp(n1:number):void; function disp(x:number,y:number):void;
Different order of parameter types:
function disp(n1:number,s1:string):void; function disp(s:string,n:number):void;
If the parameter types are different, the parameter type should be set to **any**.
If the number of parameters is different, you can make some parameters optional.
### Example
The following example defines functions with different parameter types and different numbers of parameters:
## 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 produces the following JavaScript code:
## JavaScript
function disp(x, y){console.log(x); console.log(y); }disp("abc"); disp(1, "xyz");
The output is:
abc undefined1 xyz
YouTip