JavaScript中括号用法:reducer函数外层括号的含义与用法问询
Great question! Let's break down exactly what's going on with those parentheses in your reducer function from Functional-Light JavaScript. First, let's recap the code you shared for context:
const double = v => v * 2; const reducer = (list, v) => (list.push(double(v)), list); var doubled = [1, 2, 3, 4, 5].reduce(reducer, []); console.log(doubled); // [2, 4, 6, 8, 10] var reduced = reducer([3], 2); console.log(reduced); // [3, 6]
The Core: Comma Operator + Arrow Function Implicit Return
The parentheses here are working hand-in-hand with two key JavaScript features: the comma operator and arrow function implicit returns. Let's break them down step by step:
Arrow Function Syntax Quirk
Arrow functions have two main syntax styles:- If you use curly braces
{}, you need an explicitreturnstatement to send back a value. - If you omit curly braces, the arrow function implicitly returns the single expression that follows.
Without the parentheses, JavaScript would misinterpret your code. For example,
(list, v) => list.push(double(v)), listwould treatlist.push(double(v))as the implicit return value, and the trailing, listwould be ignored as unrelated code outside the function. The parentheses wrap the entire comma expression into a single unit, so the arrow function knows to return its final result.- If you use curly braces
What the Comma Operator Does
The comma operator,lets you run multiple expressions in sequence, and it returns the value of the last expression in that sequence.In your reducer:
- First,
list.push(double(v))executes: this adds the doubled value to the array. Thepush()method returns the new length of the array, but we don't need that value here. - Then, the comma operator returns the
listvariable (the updated array)—which is exactly what thereduce()method requires, since reducers must return the updated accumulator after each iteration.
- First,
Equivalent Longhand Code
To make this even clearer, here's the same reducer written with explicit curly braces and a return statement (it behaves identically):
const reducer = (list, v) => { list.push(double(v)); return list; };
The parentheses + comma operator is just a concise way to pack this two-step logic into a single line with an implicit return.
Why This Matters for reduce()
The reduce() method depends on the reducer returning the accumulator (list here) after each loop. If we only returned the result of list.push(double(v)), we'd be sending back the array's length instead of the array itself—and reduce() would fail entirely. The comma operator ensures we run the push() side effect and return the correct accumulator value.
内容的提问来源于stack exchange,提问作者Jason Bowers

