Function Declaration or Statement
function foo(a, b) {
return a * b;
}
Function Expressions
var z = function (a, b) {return a * b};
Function Hoisting
A function created using Function Declaration or Statement can be called even before its declaration as shown in below example.
However functions created using Function Expression can only be called after it has been declared. This is the key difference between a Function Declaration and Function Expression.
console.log(foo(5));
function foo(a){
return a*a;
}
// 25
Function That Self Executes
Self Executing or Self Invoking Functions are functions that executes on its own without having to be called explicitly.
(function () {
console.log("hello")
})();
Arrow Function
Arrow functions lets you write Function Expression in short syntax.
const x = (x, y) => x * y;
First-class Function
First Class Functions or Functions are First Class citizens simply means that you can treat a function as a value. Hahah sounds funny right as Java developer, but true. You can treat a function in JS as a value i.e you can pass it as an argument and also return it as a value.
Note that a function that returns a function are also called as Higher Order Functions.
Below is an example of Higher Order Functions.
function sayTakeCare() {
return function() {
console.log("Take Care!");
}
}
sayTakeCare()();
If you noticed you will see we have used ()() twice in the function call, well its simply because the first () makes a call to sayTakeCare function which returns a function as a value. Now this function that is returned is executed by the second (). Hence two ()(). #sorted This would go on until the last return is not a function.
Below is an example of Callback Function
function sayTakeCare() {
return "Take care, ";
}
function greet(message, name) {
console.log(message() + name);
}
greet(sayTakeCare, "Rohit");
We have passed sayTakeCare function as an argument in the greet method. The greet method receives the function as a value and is executed later in the code.
This is all about functions in javaScript that i had to share. Hope it was helpful.
Happy coding !!!