Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

When finally overrides a return value in JavaScript

32 finally overriding a return

hard

Show what finally does to the value a function was already returning. Cover a return inside finally winning, the same thing swallowing a throw, the difference between reassigning the returned variable and mutating the returned object, and where continue ends up.

Stuck? Three hints, smallest first
  1. 1. The return value is captured when return runs, before finally does.
  2. 2. Captured means the reference is captured. Mutating what it points at is still visible to the caller.
  3. 3. A return in finally replaces the pending completion, whether that completion was a value or a throw.

The answer

const receipt = () => {
  try { return 'receipt LAG-0011'; }
  finally { /* release the printer, change nothing */ }
};

const overridden = () => {
  try { return 'receipt LAG-0011'; }
  finally { return 'whatever finally says'; }    // wins, silently
};

const swallowed = () => {
  try { throw new Error('printer offline'); }
  finally { return 'looks like a success'; }     // the throw is gone
};

const byValue = () => {
  let out = 'first';
  try { return out; }
  finally { out = 'changed after the return'; }  // too late: the value was taken
};

const byReference = () => {
  const out = { total: 1 };
  try { return out; }
  finally { out.total = 2; }                     // same object, so the caller sees it
};

const order = [];
const timing = () => {
  try { order.push('return computed'); return 'value'; }
  finally { order.push('finally ran'); }
};
timing();
order.push('caller resumed');

const asyncOverride = async () => {
  try { return await Promise.reject(new Error('gateway down')); }
  finally { return 'finally wins here too'; }
};
const rejectionLost = await asyncOverride();

const tills = [];
for (const till of ['ikeja', 'yaba', 'lekki']) {
  try {
    if (till === 'yaba') continue;
    tills.push(till);
  } finally {
    tills.push('closed ' + till);
  }
}

console.log('plain / overridden :', receipt(), '/', overridden());
console.log('a throw swallowed  :', swallowed());
console.log('value vs reference :', byValue(), '/', byReference());
console.log('continue           :', tills);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('an ordinary finally leaves the return value alone', receipt(), 'receipt LAG-0011');
test('but a return inside finally overrides it', overridden(), 'whatever finally says');
test('and swallows a throw completely, leaving no trace of it', swallowed(), 'looks like a success');
test('the returned value is captured before finally runs', byValue(), 'first');
test('though a mutation through the same reference still lands', byReference(), { total: 2 });
test('finally runs before the caller resumes', order, ['return computed', 'finally ran', 'caller resumed']);
test('the override applies to a rejected await as well', rejectionLost, 'finally wins here too');
test('continue runs the finally on its way out too', tills, ['ikeja', 'closed ikeja', 'closed yaba', 'lekki', 'closed lekki']);

A return in a finally block is almost always a bug, and the third assertion is why: an exception was travelling up, finally returned, and the exception simply ceased to exist. No log, no rethrow, a cheerful string handed back to a caller who now believes the receipt printed. Linters flag no-unsafe-finally for exactly this. The same goes for break, continue and throw in there.

The fourth and fifth assertions are one rule seen from two sides. return out evaluates out and keeps the result, so a later reassignment of the variable cannot reach it — but with an object, the result kept is the reference, and mutating the object afterwards is fully visible to the caller. Cleanup that resets a shared buffer you just returned is how you ship a race that only shows up under load.

The last one is the benign half of the same machinery: finally runs on every way out of the block, including continue, break and a throw, which is precisely what makes it the right place for a release. Note the ordering it produces — closed yaba appears with nothing pushed before it, because the continue skipped the body and still ran the cleanup.

Newsletter

New writing, when it lands.

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