Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Return an object from an arrow function in JavaScript

7 Returning an object literal from an arrow

easy

Write an arrow that returns { name }. Then explain why the version without parentheses returns undefined rather than failing, and find the version that is a genuine syntax error.

Stuck? Three hints, smallest first
  1. 1. After =>, a { starts a function body. The parser has no way to know you meant an object.
  2. 2. Wrap the object in parentheses so it is read as an expression: () => ({ ... }).
  3. 3. { n: n } as a body happens to be legal — n: is read as a label. Two keys is not.

The answer

const brokenToObject = (name) => { name };          // a body containing one statement
const toObject = (name) => ({ name });              // parentheses: an expression
const toPair = (key, value) => ({ [key]: value });
const rows = ['Ikeja', 'Yaba'].map((city) => ({ city, state: 'Lagos' }));

const labelled = ((n) => { n: n })(5);              // n: is a label, not a key

const parses = (src) => {
  try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; }
};

console.log('without parentheses:', brokenToObject('Ada'));
console.log('with parentheses   :', toObject('Ada'));
console.log('a labelled body    :', labelled, '<- legal, and useless');
console.log('two keys in a body :', parses('const f = (n) => { a: 1, b: 2 };'));
console.log('mapped rows        :', rows);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('braces after an arrow are a function body, not an object', brokenToObject('Ada'), undefined);
test('parentheses make it an object literal', toObject('Ada'), { name: 'Ada' });
test('a one-key body parses, because n: is read as a label', labelled, undefined);
test('two keys do not parse at all', parses('const f = (n) => { a: 1, b: 2 };'), 'SyntaxError');
test('a computed key needs the parentheses too', toPair('tier', 'gold'), { tier: 'gold' });
test('which is what makes mapping to objects readable', rows, [{ city: 'Ikeja', state: 'Lagos' }, { city: 'Yaba', state: 'Lagos' }]);
test('shorthand and longhand build the same object', same(toObject('Ada'), { name: 'Ada' }), true);

The trap is that the broken version is not an error. (name) => { name } is a function whose body evaluates name and throws the result away, so you get undefined and no complaint. In a map that produces an array of undefined, and the failure surfaces several layers later.

The third assertion explains why the parser cannot help you: { n: n } really is valid as a body, with n: as a statement label. Only when you write a second key does it become ambiguous enough to reject.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.