A function expression is very similar to, and has almost the same syntax as, a function declaration.
The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions.
Function Expression with name is known as Named Function Expression aka NFE
Examples of function expressions:
// Using unnamed functionconst a = function (y) { return y * y;};// Using named functionconst b = function namedFunc(z) { return 2 * z;}// Using function as callbackbutton.addEventListener("click", function (event) { console.log("button is clicked!");});// Using an Immediately Invoked Function Expression (IIFE)(function () { console.log("Code runs!");})();
Immediately Invoked Function Expression (IIFE)
As described in the above example, we can create a function expression and immediately call it. Also we can pass variables as well:
Function Expression and Function Declaration Hoisting
Unlike Function Declaration, you cannot use Function Expression before you declare it
console.log(notHoisted); // undefined// Even though the variable name is hoisted,// the definition isn't. so it's undefined.notHoisted(); // TypeError: notHoisted is not a functionvar notHoisted = function () { console.log("bar");};
But Function Declaration is fully hoisted and hence can be used before you declare it