Learnt JavaScript
Learned reactjs

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:

  1. In JavaScript, hoisting refers to the availability of the variables and the functions at the beginning of the code.
  2. 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:

  1. In JavaScript, a callback is a function that is passed to another function as an argument.
  2. 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:

  1. An Immediately-invoked Function Expression (IIFE) is a function that is executed at the time of its creation.
  2. IIFE can be declared using function expression only.

(() => {
  console.log("Hi");
})();