1. Function Declaration
This is the basic way to create a function.
Example:
function sayHello() {
console.log("Hello");
}
sayHello();
Output:
Hello
2. Function Expression
Here, the function is stored in a variable.
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 (0)