Sobes.tech
Junior

What is a functional expression and what is it used for?

sobes.tech AI

Answer from AI

A functional expression is a definition of a function within another expression. It is not declared as a separate operator function name(...) {}, but is assigned to a variable, an object property, or used as an argument to another function.

Purpose:

  • Creating anonymous functions: Allows defining a function without a name, useful for callbacks or one-time functions.
  • Closures: Functional expressions are often used to create closures, enabling a function to "remember" variables from the outer scope even after the outer function has finished executing.
  • Immediately Invoked Function Expressions (IIFE): Provide code isolation and prevent pollution of the global scope.
  • Dynamic function creation: Functions can be created and assigned depending on the execution conditions of the program.

Example of an anonymous functional expression:

// Assigning an anonymous function to a variable
const greet = function(name) {
  console.log(`Hello, ${name}!`);
};

greet("World");

Example of an IIFE:

(function() {
  // Code inside this function executes immediately
  // and variables inside it are not accessible from outside
  let privateVariable = "secret";
  console.log(privateVariable);
})();

// console.log(privateVariable); // Error: privateVariable is not defined