Function Expression
Function Expression
Section titled “Function Expression”Introduction
Section titled “Introduction”A function expression assigns a function to a variable. Unlike declarations, function expressions are not hoisted.
Syntax
Section titled “Syntax”const functionName = function(parameters) { // body};Example
Section titled “Example”const greet = function(name) { return `Hello, ${name}!`;};
console.log(greet('Alice')); // 'Hello, Alice!'Not Hoisted
Section titled “Not Hoisted”// ❌ This throws an error!sayHello(); // ReferenceError
const sayHello = function() { console.log('Hello!');};Visual Explanation
Section titled “Visual Explanation”flowchart TD A["Function Expression"] B["const greet = function(name) { return '...'; }"] C["❌ Not hoisted"] D["✅ Stored in a variable"] E["✅ Can be anonymous or named"]
A --> B B --> C B --> D B --> ENamed Function Expressions
Section titled “Named Function Expressions”const greet = function sayHello(name) { return `Hello, ${name}!`;};// The name 'sayHello' is only accessible inside the functionWhen to Use
Section titled “When to Use”- Assigning functions conditionally
- Passing as callbacks
- Creating functions inside blocks
- Used as IIFE (Immediately Invoked Function Expression)
Summary
Section titled “Summary”- Function expressions are NOT hoisted
- They are assigned to variables
- Useful for callbacks and conditional assignments