Function Expressions

Functions as values. Store them, pass them, return them.

Expression vs Declaration

Two ways to create functions — different behavior.

// Function Declaration:
function greet(name) {
  return "Hello, " + name;
}

// ✓ Hoisted — can call before definition
// ✓ Has a name in stack traces
// ✓ Stands alone as a statement

✓ Hoisted to top of scope

// Declaration: works before definition
sayHi(); // "Hi!" ← hoisted
function sayHi() { return "Hi!"; }

// Expression: error before definition
sayBye(); // TypeError!
const sayBye = function() { return "Bye!"; };
TypeError: sayBye is not a function

Anonymous Functions

Functions without a name — used as values.

// Anonymous — no name after 'function':
const greet = function(name) {
  return "Hello, " + name;
};

// Named expression — has a name:
const greet = function greetFn(name) {
  return "Hello, " + name;
};
// greetFn is only visible inside itself (for recursion)
// Outside, only 'greet' works

Common uses of anonymous functions:

// 1. Array callbacks:
[1, 2, 3].map(function(n) { return n * 2; });

// 2. Event handlers:
button.addEventListener("click", function() {
  console.log("clicked");
});

// 3. Immediately executed:
(function() {
  console.log("runs now!");
})();

First-Class Functions

In JavaScript, functions are values — just like numbers or strings.

Store in variable

const fn = function() {}

Store in array

const fns = [fn1, fn2]

Pass as argument

arr.map(fn)

Return from function

return function() {}

// Functions as object values:
const math = {
  add: function(a, b) { return a + b; },
  sub: function(a, b) { return a - b; },
};
math.add(2, 3); // 5

// Functions in an array:
const transforms = [
  function(x) { return x * 2; },
  function(x) { return x + 10; },
  function(x) { return x ** 2; },
];
transforms[0](5); // 10

IIFE

Immediately Invoked Function Expression — runs as soon as defined.

// IIFE pattern:
(function() {
  const secret = "hidden";
  console.log("I run immediately!");
})();

// 'secret' is not accessible here
// console.log(secret); // ReferenceError
// With parameters:
(function(name) {
  console.log("Hello, " + name);
})("World");
// "Hello, World"

You can pass arguments to an IIFE just like any function call.

1 / 2

FAQ

Common questions about function expressions.