JavaScript Function Expressions

JavaScript Function Expressions

JavaScript Function Expressions

A function expression is a function that is assigned to a variable. Unlike function declarations, function expressions are not hoisted and must be defined before use.

1️⃣ Syntax

const functionName = function(parameters) { // Code to execute return result; };

2️⃣ Example: Function Expression

const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet("John")); // Output: Hello, John!

šŸ“Œ Key Difference from Function Declarations:

  • Function declarations are hoisted, meaning they can be used before they are defined.
  • Function expressions are not hoisted, meaning they must be defined before use.

3️⃣ Anonymous Function Expression

A function without a name, assigned to a variable.

const sum = function(a, b) { return a + b; }; console.log(sum(5, 3)); // Output: 8

šŸ“Œ The function has no name but is stored in the sum variable.

4️⃣ Named Function Expression

A function with a name, assigned to a variable.

const factorial = function fact(n) { if (n === 0) return 1; return n * fact(n - 1); }; console.log(factorial(5)); // Output: 120

šŸ“Œ Here, fact(n) is a function name only available inside the function.

5️⃣ Function Expressions as Arguments

Function expressions can be passed as arguments to other functions.

function operate(a, b, callback) { return callback(a, b); } const multiply = function(x, y) { return x * y; }; console.log(operate(4, 5, multiply)); // Output: 20

6️⃣ Arrow Functions (ES6) as Function Expressions

A shorter syntax for function expressions.

const square = (n) => n * n; console.log(square(6)); // Output: 36

7️⃣ Immediately Invoked Function Expression (IIFE)

A function that runs immediately after being defined.

(function() { console.log("I run immediately!"); })();

šŸ“Œ Useful for:
✅ Avoiding pollution of global scope
Isolating variables in their own scope

šŸŽÆ Summary

Function Expressionconst sum = function(a, b) { return a + b; };
Anonymous Function Expression → No function name
Named Function Expression → Can reference itself
Used as Arguments → Pass functions into other functions
Arrow Functionsconst square = n => n * n;
IIFE(function() { console.log("Runs immediately!"); })();

šŸš€ Now you understand function expressions! Let me know if you need help. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close