1. Function Declaration
This is the basic way to create a function.
Example:
function sayHello() {
console.log("Hello");
}
sayHello();
Output:
Hello
2. Function Expression
A function expression is a function that is created and assigned to a variable (or used as a value).
Example:
const sayHello = function() {
console.log("Hello");
};
sayHello();
Output:
Hello
3. Arrow Function (Lambda)
Short and modern way to write functions.
Example:
const sayHello = () => {
console.log("Hello");
};
sayHello();
Output:
Hello
4. Anonymous Function
Function without a name.
Example:
const greet = function() {
return "Hi there!";
};
console.log(greet());
Output:
Hi there!
5. Callback Function
A function passed inside another function.
Example:
function greet(name, fun) {
fun(name);
}
greet("Ram", function(name) {
console.log("Hello " + name);
});
Output:
Hello Ram
6. IIFE (Immediately Invoked Function)
Runs immediately after writing.
Example:
(function() {
console.log("Run now");
})();
Output:
Run now
7. Constructor Function
Used to create objects.
Example:
function Person(name) {
this.name = name;
}
let p1 = new Person("Ram");
console.log(p1.name);
Output:
Ram
8. Generator Function
Used to return values one by one.
Example:
function* num() {
yield 1;
}
let n = num();
console.log(n.next().value);
Output:
1
Top comments (4)
Function expression and storing a function in a variable are two different things. You haven't explained what function expression is.
What is the function expression? We should put the function inside the variable that is called a function expression .
Function expression occurs when the
functionkeyword is used at a point in the code where a statement would be illegal - i.e. as part of an expression. In this situation it kind of functions as a 'function literal' - defining a function in-place, but not assigning it to any variable. A function created in this manner CAN be assigned to a variable - and often is... but the act of assigning it to a variable has nothing to with it being function expression.Function expressions are often used to create anonymous callbacks to pass to other functions, and are also frequently seen in IIFEs - hence the name 'Immediately Invoked Function Expression'.
thanks for the explanation sir