HomeAbout

Functions

Functions

// 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!"); }

Differences

Function Declaration is hoisted, meaning it can be used before it is declared.

  • Created as a property in the Variable Object (VO) of its context

Function Expression and Arrow Function are not hoisted, meaning they cannot be used before they are declared.

  • Variable holds a reference to the function.

What is 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.

Callback Functions

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.

Passing Function as an Argument

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!"); })();

What is 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!"); })();

Difference between IIFE and Function Declaration

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.

  • If you pass in a IIFE as an argument, it will pass the resulting value of the IIFE as an argument, not the function itself.
AboutContact