Skip to content

Function Expression

A function expression assigns a function to a variable. Unlike declarations, function expressions are not hoisted.

const functionName = function(parameters) {
// body
};
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet('Alice')); // 'Hello, Alice!'
// ❌ This throws an error!
sayHello(); // ReferenceError
const sayHello = function() {
console.log('Hello!');
};
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 --> E
const greet = function sayHello(name) {
return `Hello, ${name}!`;
};
// The name 'sayHello' is only accessible inside the function
  • Assigning functions conditionally
  • Passing as callbacks
  • Creating functions inside blocks
  • Used as IIFE (Immediately Invoked Function Expression)
  • Function expressions are NOT hoisted
  • They are assigned to variables
  • Useful for callbacks and conditional assignments