Trace the fixed program
Two functions double 4. One writes 8 into a transcript; the other returns 8. The transcript models a log without adding a second console line.
const transcript=[];
function loggedDouble(n){transcript.push(n*2);}
function returnedDouble(n){return n*2;}
const result={logged:typeof loggedDouble(4),returned:returnedDouble(4),transcript};
console.log(JSON.stringify(result));
{"logged":"undefined","returned":8,"transcript":[8]}| Function | Recorded effect | Caller receives |
|---|---|---|
| loggedDouble(4) | transcript: [8] | undefined |
| returnedDouble(4) | No transcript write | 8 |
Explain the result
A function that reaches its end without return supplies undefined to its caller. Recording a number is a separate side effect. typeof preserves the undefined observation in JSON, which would otherwise omit an undefined object value.
Test the alternative
Adding 1 to the logged function result yields NaN, even though its transcript contains 8. String() makes NaN explicit rather than JSON null.
const transcript=[];function loggedDouble(n){transcript.push(n*2);}
console.log(JSON.stringify({next:String(loggedDouble(4)+1),transcript}));
{"next":"NaN","transcript":[8]}Work the boundary case
How can loggedDouble keep its record and allow the caller to calculate 9?
Show the worked answer
Store n*2, append it to the transcript, then return that value. The caller can add 1 to the returned 8.
const transcript=[];function doubled(n){const value=n*2;transcript.push(value);return value;}
console.log(JSON.stringify({zero:doubled(0),next:doubled(4)+1,transcript}));
{"zero":0,"next":9,"transcript":[0,8]}