Sub topic 3
Function Expressions
This chapter assumes you can declare variables with var, let, and const, write object literals with methods, and pass a callback to something like setTimeout or Array.prototype.map. You should also have read the previous chapter on function declarations, because this chapter keeps comparing the two.
A function expression creates a function in a position where JavaScript expects a value. A function declaration is a statement that introduces a name into the scope. A function expression produces a function object, and you decide what to do with it: store it in a variable, put it in an object, pass it to another function, or return it.
The Basic Shape
The most common function expression is an anonymous function assigned to a variable:
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(3, 4)); // 12
console.log(typeof multiply); // "function"The right-hand side of the = is the function expression. The function keyword, the parameter list, and the body are the same as in a declaration. The parts that differ are:
- The name after
functionis optional, and here it is omitted. - The whole construct is an expression, so the statement ends with a semicolon, just like
const x = 5;. - The variable
multiplyfollows the rules ofconst. It is block-scoped and cannot be reassigned.
The function itself is not tied to the variable. The variable holds a reference to a function object, and other variables can hold the same reference:
const multiply = function (a, b) {
return a * b;
};
const times = multiply;
console.log(times(2, 5)); // 10
console.log(times === multiply); // trueHow the Parser Tells Declarations and Expressions Apart
Both forms start with the function keyword, so the parser decides which one it is reading from the position of the code. If a statement starts with function, the parser reads a declaration. Anywhere a value is expected, such as after =, inside parentheses, as an argument, after return, or inside an array or object literal, it reads an expression.
This rule explains an error that surprises people. An anonymous function at the start of a statement is a syntax error, because the parser expects a declaration and declarations must have a name. Wrapping the function in parentheses puts it in expression position:
try {
eval('function () {}');
} catch (e) {
console.log(e instanceof SyntaxError); // true
}
const value = (function () {
return 'ok';
});
console.log(typeof value); // "function"eval is used here only so the syntax error can be caught and printed. If you wrote function () {} directly in a file, the whole script would fail to parse and none of it would run.
Where Function Expressions Appear
Variable assignment is only one place you will see function expressions. They show up anywhere you need a function as a value.
As Callbacks
Passing an inline function to another function is the most common use:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function (n) {
return n * 2;
});
const evens = numbers.filter(function (n) {
return n % 2 === 0;
});
console.log(doubled); // [ 2, 4, 6, 8 ]
console.log(evens); // [ 2, 4 ]Each function (n) { ... } is created when its line runs and is handed to map or filter, which call it once per element. In modern code these callbacks are usually written as arrow functions, which a later chapter covers. Regular function expressions still appear often in older code and in places where this behavior matters.
As Object Properties
A function expression can be the value of a property:
const calculator = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // 8
console.log(calculator.subtract(5, 3)); // 2The shorthand method syntax add(a, b) { ... } is more common today. It is close to a property holding a function expression, though shorthand methods cannot be used with new, and they can use super.
As Return Values
Because a function expression is a value, a function can build and return one. The returned function keeps access to the variables of the function that created it. This is called a closure:
function makeMultiplier(factor) {
return function (n) {
return n * factor;
};
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(10)); // 20
console.log(triple(10)); // 30Each call to makeMultiplier evaluates the inner function expression again and creates a new function object with its own factor. That is why double and triple behave differently even though their source code is the same.
Chosen at Runtime
A declaration always defines the same function. With an expression, you can pick which function to create based on conditions when the code runs:
const verbose = process.argv.includes('--verbose');
const log = verbose
? function (msg) { console.log(`[${new Date().toISOString()}] ${msg}`); }
: function (msg) { console.log(msg); };
log('Starting');Run it with node file.js for plain output, or node file.js --verbose to get timestamps. You can do something similar with declarations inside if blocks, but as a later chapter shows, block-level declarations have inconsistent legacy behavior. The expression version is clear and predictable.
Name Inference
An anonymous function expression has no name in its source code, yet it usually gets one. When you assign an anonymous function to a variable or a property, the engine sets the function's name property from the binding:
const multiply = function (a, b) {
return a * b;
};
const ops = {
double: function (x) {
return x * 2;
}
};
const list = [function () {}];
console.log(multiply.name); // "multiply"
console.log(ops.double.name); // "double"
console.log(list[0].name); // ""Inference only happens for certain syntactic forms: variable declarations, assignments, default values, and property definitions in object literals. A function placed in an array, passed directly as an argument, or reassigned through another variable later gets no inferred name, or keeps the one it already had. The name property is what stack traces and debuggers show, so anonymous callbacks often appear as <anonymous> in error output. The chapter on named function expressions shows how to give a function an explicit name that stays fixed.
Choosing `const`, `let`, or `var`
The variable that holds a function expression has normal variable semantics. That gives you control a declaration does not:
| Binding | Can be reassigned | Scope | Usable before the line runs |
|---|---|---|---|
| `const` | No | Block | No, throws `ReferenceError` |
| `let` | Yes | Block | No, throws `ReferenceError` |
| `var` | Yes | Function | Variable exists but is `undefined`, calling it throws `TypeError` |
| Function declaration | Yes | Function, or block in strict mode | Yes, the whole function is available |
Use const by default. It stops another part of the code from accidentally replacing your function. Use let only when you really intend to swap the function later, for example to replace a handler:
let handler = function (event) {
return `default: ${event}`;
};
console.log(handler('click')); // default: click
handler = function (event) {
return `custom: ${event}`;
};
console.log(handler('click')); // custom: clickThe last column of the table is the big behavioral difference from declarations. A function expression does not exist until the line that creates it has run. The next chapter covers exactly what happens if you call it too early, including the temporal dead zone.
Common Errors
Forgetting the Semicolon
A declaration does not need a trailing semicolon, but an assignment of a function expression does. Usually automatic semicolon insertion (ASI) adds it for you. ASI does not add a semicolon if the next line starts with ( or [, because those characters can continue the previous expression:
let result;
try {
result = function () {
return 1;
}
(function () {
console.log('setup');
})();
} catch (e) {
console.log(e instanceof TypeError); // true
}JavaScript reads this as one expression: it calls the first function with the second function as an argument, gets back 1, and then tries to call 1(). The text setup is never printed. Ending every function expression assignment with ; prevents this.
Confusing the Function with Its Result
Passing fn passes the function. Passing fn() calls it right away and passes whatever it returns:
const sayHi = function () {
console.log('hi');
};
setTimeout(sayHi, 0); // logs "hi" later
// setTimeout(sayHi(), 0); // logs "hi" now, then passes undefinedThis bug often does not crash. setTimeout accepts undefined and does nothing with it, so the only sign is that the timing is wrong.
Expecting the Function to Exist Earlier
Code like const f = function () {} creates the function only when that line runs. If you move a helper call above its definition, a declaration would keep working, but a function expression throws. This is a deliberate trade-off. Expressions make the order of your code matter, which some teams prefer because the file reads top to bottom.
Exercise
What do the two console.log calls print, and why?
const pick = function (flag) {
return flag ? function () { return 'A'; } : function () { return 'B'; };
};
const f = pick(false);
console.log(f());
console.log(f.name);
Show answer
The first prints "B", because pick(false) returns the second function expression and calling it returns 'B'. The second prints an empty string. The returned function is created inside a conditional expression and passed back through return, so no name is inferred for it. Assigning it to const f later does not rename it, because inference only applies when the anonymous function expression itself appears directly on the right-hand side of the binding.
Exercise
The following line causes a SyntaxError. Give two different ways to fix it so the script runs and the function is usable as a value. function (x) { return x + 1; }
Show answer
The function is at the start of a statement, so the parser reads it as a declaration, and declarations need a name. Fix 1: put it in expression position by assigning it, as in const addOne = function (x) { return x + 1; }; Fix 2: give it a name so it becomes a valid declaration, as in function addOne(x) { return x + 1; }. Wrapping it in parentheses, (function (x) { return x + 1; }), also parses, but the function is then discarded unless you use it right away.
Exercise
Rewrite makeCounter so it returns an object with increment and current properties, each a function expression sharing a private count variable. What does calling increment twice and then current print?
Show answer
function makeCounter() { let count = 0; return { increment: function () { count += 1; }, current: function () { return count; } }; } const c = makeCounter(); c.increment(); c.increment(); console.log(c.current()); prints 2. Both function expressions are closures over the same count variable created by that call to makeCounter.