Function Expressions

  • 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 function
const a = function (y) {
  return y * y;
};
 
// Using named function
const b = function namedFunc(z) {
	return 2 * z;
}
 
// Using function as callback
button.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 printName(lastName) {
    const firstName = "John";
    return firstName + " " + lastName;
})("Doe"); // 'John Doe'

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 function
 
var notHoisted = function () {
  console.log("bar");
};
  • But Function Declaration is fully hoisted and hence can be used before you declare it
hoisted(); // Logs "foo"
 
function hoisted() {
  console.log("foo");
}