Lesson 26 +15 XP

Function Expressions and Callbacks

Function Expressions and Callbacks

Functions can also be stored in variables, passed around, and given as arguments.

Function expression

A function stored in a variable:

const greet = function() {
  console.log("Hello!");
};
greet();

The variable name is how you call it.

Anonymous functions

Functions without a name are anonymous. They are usually stored in a variable or passed directly:

const greet = function() { ... }; // anonymous, stored in greet

Callbacks

A callback is a function passed as an argument to another function, to be called later:

function process(value, callback) {
  let result = value * 2;
  callback(result);
}

process(5, function(result) {
  console.log("Result: " + result);
});

Why callbacks?

  • They let you say "when this is done, run this".
  • Essential for events and async work.
  • Built-in methods like forEach use callbacks.
[1, 2, 3].forEach(function(n) {
  console.log(n);
});

TL;DR

  • Functions can be stored in variables.
  • Anonymous functions have no name.
  • Callbacks are functions passed to other functions.
  • Callbacks run later, often after an event or task.