A function is a set of statements execute to achieve a specific task.
we will discuss on:
- basic function
- function with optional param
- function with rest param
- Anonymous function
1. Basic function:
syntax:
1 2 3 |
function functionName() { // task } |
code example:
1 2 3 4 5 6 |
function sumNumber() { let sum = 4 + 5; console.log(sum) } sumNumber(); |
output: 9
2. Function with optional param:
In the below example, email is the optional param as it it marked with ‘?’.
An optional param does not need argument to pass. in below example e-mail as arg not been passed to method and still execute successfully.
1 2 3 4 5 |
function myDetail(name: string, rollNumber: Number, email?: string) { console.log("details are " + name + " " + rollNumber) } myDetail("shri", 123) |
Output: details are shri 123
3. Function with rest param:
- This function is same as variable arg in java.you
- It does not defined the number of param.
- It uses syntax ” ...variable:dataype ” as param.
- The rest param work on only one type of data type. eg. all param can be considered for rest param if they doing for all number or string or array.
example code:
1 2 3 4 5 6 7 8 9 |
function add(...nums: number[]): number { let sum = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i] } return sum; } let result = add(2, 3, 4); console.log(result); |
Output: 9
4. Anonymous function :
A function with no name and just body definition called Anonymous function.
for example:
1 2 3 4 5 |
let anonymousFunc = () => { console.log("hello world") } anonymousFunc(); |
Output: hello world