liveBook · Manning

Function expression

As explained in Secrets of the JavaScript Ninja, Third Edition

A function expression is a JavaScript expression that creates a function and occurs as part of another expression or statement.

Need a function for one assignment or one call? A function expression creates a function where JavaScript expects a value. It can sit on the right side of an assignment, serve as an argument, or be returned from another function. Because functions are first-class objects, the resulting function can also be stored in a variable or property. section 5.1.1

let a = function() {};
myFunction(function(){});

These two placements show the idea: assign a function to a variable, or create one directly as a call argument. section 5.1.1

The contrast with a function declaration is about placement. A declaration is its own statement and requires a name; an expression is part of another statement and need not have a name. For example, `const doNothing = function() {};` creates a function value and assigns it to `doNothing`. Calling `doNothing()` happens afterward. section 5.1 section 5.1.1

Create a function where it is needed

In `myFunc(function() { return function() {}; });`, the argument to `myFunc` is a function expression. Its return value is another function expression. A function expression can also be named and called immediately: `(function namedFunctionExpression() {})();` The parentheses put the function in expression position before the call. section 5.1.1

Use an expression when a function belongs at the point where a value is needed, rather than as a separate declaration. Arrow functions offer another syntax; their handling of `this` differs, so the choice is not always cosmetic. section 5.1.1 section 5.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines expression placement through examples and contrasts it with declarations; defers detailed scope and identifier resolution.
Examples
Shows anonymous functions assigned to variables, passed as arguments, returned from functions, and called immediately.
What it assumes
Assumes familiarity with variables, assignments, and function calls while teaching the declaration-versus-expression distinction explicitly.
What you can do after
Build it from scratch: place a function expression in an assignment, argument, return statement, or immediate call.
How it connects
Connects function expressions to first-class functions, function declarations, arrow functions, and callbacks.

Also explained in

Compare how 2 books explain function expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.