Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Function Expression

Learn to use function expressions. Master assigning functions to variables, callbacks, and IIFE patterns.

Why this matters

Function expressions treat functions as values. This enables powerful patterns like passing functions as arguments, creating callbacks, and building functional programming patterns essential to modern JavaScript.

What is Function Expression?

A function expression assigns a function to a variable. The function can be named or anonymous (without a name). Unlike function declarations, function expressions are not hoisted.

Function expressions allow functions to be treated as values - you can assign them to variables, pass them as arguments, and return them from other functions.

Basic Function Expression

// Anonymous function expression
const greet = function(name) {
  return "Hello, " + name;
};

console.log(greet("Alice")); // Hello, Alice

// Named function expression
const add = function sum(a, b) {
  return a + b;
};

console.log(add(5, 3)); // 8

Function expressions use the function keyword but assign to a variable. The function name is optional.

Function Expression vs Function Declaration

The main differences are hoisting behavior and how they're defined. Function declarations are hoisted and can be called before they're written, while function expressions cannot.

Hoisting Differences

// Function Declaration - HOISTED (works)
console.log(declare(5));  // Works: 10

function declare(x) {
  return x * 2;
}

// Function Expression - NOT hoisted (error)
console.log(express(5)); // ReferenceError: express is not defined

const express = function(x) {
  return x * 2;
};

Function declarations are hoisted to the top of their scope. Function expressions are not.

Why Use Function Expressions?

Function expressions are useful when you need to pass functions as arguments, store them in data structures, or return them from other functions.

Functions as Arguments

// Function expression passed as argument
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(function(num) {
  return num * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]

// Function expression as callback
setTimeout(function() {
  console.log("This runs after 2 seconds");
}, 2000);

Function expressions let you pass functions directly to other functions like callbacks.

Storing Functions in Variables

const operations = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  },
  multiply: function(a, b) {
    return a * b;
  }
};

console.log(operations.add(10, 5));      // 15
console.log(operations.subtract(10, 5)); // 5
console.log(operations.multiply(10, 5)); // 50

You can store function expressions in object properties to create methods.

Anonymous vs Named Function Expressions

Function expressions can be anonymous (no name) or named. Named function expressions can reference themselves, which is useful for recursion.

Named Function Expression

// Anonymous - can't refer to itself
const factorial1 = function(n) {
  if (n <= 1) return 1;
  // Can't call 'factorial1' easily here
  return n * factorial1(n - 1); // Works but relies on variable name
};

// Named - can refer to itself by function name
const factorial2 = function fact(n) {
  if (n <= 1) return 1;
  return n * fact(n - 1); // Uses the function name 'fact'
};

console.log(factorial1(5)); // 120
console.log(factorial2(5)); // 120

Named function expressions can reference themselves using their function name.

Immediately Invoked Function Expression (IIFE)

An IIFE is a function expression that runs immediately after it's defined. It's useful for creating private scopes.

IIFE Example

// IIFE - the function runs immediately
(function() {
  console.log("This runs immediately");
  const secret = "hidden";
})();

// Can't access 'secret' from outside
console.log(secret); // ReferenceError

// IIFE with parameters
(function(name) {
  console.log("Hello, " + name);
})("World");

// IIFE returning a value
const result = (function() {
  return 5 + 3;
})();

console.log(result); // 8

IIFE creates a private scope and runs immediately. Useful for avoiding global variable pollution.

When to Use Function Expressions

Use function expressions when you need functions as values, when you want to avoid hoisting issues, or when you need to pass functions around.

  • Use when passing functions as arguments to other functions
  • Use for callback functions in event handlers or timers
  • Use when storing functions in objects or arrays
  • Use when you want to create private scopes with IIFE
  • Use when you need to ensure functions are defined before use

Common Mistakes

  • Calling before definition: Function expressions are not hoisted. Always define them before calling.
  • Missing semicolon: Always end function expressions with a semicolon, even though it's technically optional.
  • Confusing named and anonymous expressions: The function name in a named expression is only available inside the function, not outside.

FAQ

What's the difference between function expression and declaration?

Function declarations are hoisted and can be called before definition. Function expressions are not hoisted and must be defined before use.

Can I use a named function expression?

Yes, named function expressions let the function refer to itself, which is useful for recursion or debugging.

What is an IIFE?

IIFE (Immediately Invoked Function Expression) is a function expression that runs immediately after being defined. It creates a private scope.