// Function Declaration function myFunctionDeclaration() { console.log("Hello, world!"); } // Function Expression const myFunctionExpression = function() { console.log("Hello, world!"); } // Arrow Function (syntactic sugar for Function Expression) const myArrowFunction = () => { console.log("Hello, world!"); }
Function Declaration
is hoisted
, meaning it can be used before it is declared.
Variable Object (VO)
of its contextFunction Expression
and Arrow Function
are not hoisted, meaning they cannot be used before they are declared.
VO
VO
stands for Variable Object
.
A special object created for each execution context (like function or global scope).
It contains all the variables, functions, and arguments for that execution context.
A callback function is a function that is passed as an argument to another function.
// Callback Function function callbackFunction() { console.log("Hello, world!"); } // Passing a Callback Function someFunction(callbackFunction);
Methods like forEach
, map
, filter
, reduce
, etc. take a callback function as an argument.
array.map(callbackFunction);
In this case, the declaration is passed as an argument, not the function itself.
const myFunctionDeclaration = function() { console.log("Hello, world!"); } // Passing Function (callback) someFunction(myFunctionDeclaration); // Passing a Return Value of a Function someFunction(myFunctionDeclaration()); // Passing an IIFE (passing a Function Return Value) someFunction((function myFunctionDeclaration() { console.log("Hello, world!"); })()); // IIFE in this case has the same effect as passing a Function Return Value someFunction(function() { console.log("Hello, world!"); })();
IIFE
IIFE
stands for Immediately Invoked Function Expression
.
It's a way to create a function and immediately execute it upon declaration.
(function() { console.log("Hello, world!"); })();
When passed to a function as an argument, IIFE
is executed immediately while Function Declaration
is not.
//Function Declaration function myFunction() { console.log("Hello, world!"); } // IIFE (function() { console.log("Hello, world!"); })();
IIFEs
cannot be used as a callback function because they are executed immediately.