Function Declaration vs Function Expression!
Function Declaration:
A function declaration defines a function with the specified parameters. The function declarations are processed before the code block is executed. They are visible everywhere in the block.
function sayHi () { ...some code here }
Function Expression:
A function expression is a function that is stored in a variable. The function expressions are created when the execution flow reaches them.
const sayHi = function () { ...some code here }
Difference:
Hoisting:
- In JavaScript, hoisting refers to the availability of the variables and the functions at the beginning of the code.
- Function expressions will load only when the interpreter reaches it.
1. sayHi(); 2. const sayHi = function () { console.log('Hi'); }
The above code will throw an error because the sayHi function is called before it reaches line 2.
Callback:
- In JavaScript, a callback is a function that is passed to another function as an argument.
- If a callback is a function expression, it will not be available outside of the function that uses it.
const sayHi = function () { console.log('Hi'); } const greetings = (func) => { func(); } greetings(sayHi);
So, in the above code, the sayHi function will also be present global. To avoid this we can use the function expression as below code.
const greetings = (func) => { func(); } greetings( () =>{ console.log('Hi'); });
Here the callback function will not be in the global scope.
IIFE:
- An Immediately-invoked Function Expression (IIFE) is a function that is executed at the time of its creation.
- IIFE can be declared using function expression only.
(() => { console.log("Hi"); })();