Trace the fixed program
A draft note is stored in a const binding. Predict whether changing its title and replacing the entire note are the same operation.
const note={title:'Draft'}; note.title='Revised';
let reassignment; try{note={title:'Other'};}catch(error){reassignment=error.name;}
console.log(JSON.stringify({title:note.title,reassignment}));
{"title":"Revised","reassignment":"TypeError"}| Operation | Target | Observed result |
|---|---|---|
| note.title='Revised' | Object property | Revised |
| note={...} | Constant binding | TypeError |
Explain the result
note keeps the same object reference. The title assignment writes inside that object; assigning a new object to note is rebinding and throws TypeError. The catch records only the error name, avoiding engine-dependent wording.
Test the alternative
const does not freeze nested values. Even freezing the outer note leaves its nested style editable in this example.
const note=Object.freeze({style:{ink:'green'}});
note.style.ink='purple';
console.log(JSON.stringify({outerFrozen:Object.isFrozen(note),innerFrozen:Object.isFrozen(note.style),ink:note.style.ink}));
{"outerFrozen":true,"innerFrozen":false,"ink":"purple"}Work the boundary case
Would changing const to let make note.title immutable?
Show the worked answer
No. let permits rebinding too; it adds no object protection. Choose explicit copying or a suitable freeze policy if that is the requirement.
'use strict';
const note=Object.freeze({title:'Draft'});let errorName;
try{note.title='Revised';}catch(error){errorName=error.name;}
console.log(JSON.stringify({title:note.title,errorName}));
{"title":"Draft","errorName":"TypeError"}