function and anonymous function , type of function
function & anonymous function :
- The key difference between a function and an anonymous function lies in how they are defined and used. Let's break it down.
Named Function (Regular Function):
- A named function is a function that has a name by which it can be invoked.
const add = function (a: number, b: number): number {
return a + b;
};
add(10, 20); // Calling the function using the variable name "add"
Anonymous Function:
- An anonymous function is a function without a name. It is typically used in situations where a function is passed as an argument or assigned to a variable.
const add = function (
a: number, b: number): number {
return a + b;
};
add(10, 20); // Calling the function using the variable name "add"
Comparison:
Aspect | Named Function | Anonymous Function |
---|---|---|
Name | Has a name (e.g., add ) | No name; assigned to a variable |
Usage | Called by its name | Called using the variable it’s assigned to |
Hoisting | Can be called before it’s defined | Cannot be called before it’s defined |
Common Usage | Reusable code blocks, function declarations | Event handlers, callbacks, inline functions |
Types of Functions in TypeScript:
Named Functions:
- These functions have a name and can be called by that name.
function greet(name: string): string {
return 'Hello' + name;
}
let message = greet ("ram");
console.log( message ); // hello ram
Arrow Functions :
- Arrow functions are a shorter way to write functions in JavaScript and TypeScript.
- They use the
=>
syntax,
// Arrow function
const added = (a: number , b : number )=> a+b;
console.log( added (30,40));
Optional Parameters:
- An optional parameter is a parameter you can choose to provide or leave out calling a function.
- you make a parameter optional by adding a question mark (
?
) after its name.
interface person {
person_id :number;
person_name: String ;
person_dep :string;
person_age?:number
}
let person : person ={
person_id : 10,
person_name: "ram",
person_dep : "mca"
// person_age?:number Optional Parameters
}
console.log( person );
Rest parameter :
- JavaScript (and TypeScript) allows you to represent an indefinite number of
Comments
Post a Comment