JavaScriptFundamental (ES6), part 1
const vs Object.freeze in JavaScript
5 const with a mutable object
easyShow that a const object can be modified while the binding cannot be reassigned. Then use Object.freeze to stop the modification too, and report what happens under strict mode.
Stuck? Three hints, smallest first
- 1.
constis a promise about the binding: this name will keep pointing at this value. - 2.
Object.freezeis a promise about the value: nobody may add, remove or change a property. - 3. A panel here runs in strict mode, so a write to a frozen property throws rather than being ignored.
const account = { owner: 'Adaeze', balanceNgn: 25000 };
account.balanceNgn += 5000; // the value is not const
const rebind = (() => {
try { account = { owner: 'someone else' }; return 'allowed'; }
catch (e) { return e.constructor.name; }
})();
const branches = ['Ikeja'];
branches.push('Yaba');
const card = Object.freeze({ tier: 'gold' });
const frozenWrite = (() => {
try { card.tier = 'silver'; return 'allowed'; }
catch (e) { return e.constructor.name; }
})();
const constInAClassicLoop = (() => {
try { for (const i = 0; i < 3; i++); return 'ran'; }
catch (e) { return e.constructor.name; }
})();
console.log('balance after +5000 :', account.balanceNgn);
console.log('rebinding the const :', rebind);
console.log('pushing to a const array:', branches);
console.log('writing to a frozen object:', frozenWrite, '<- strict mode, so it throws');
console.log('const in a for(;;) header :', constInAClassicLoop);
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.
test('a const object can still be changed', account.balanceNgn, 30000);
test('but the binding cannot be pointed somewhere else', rebind, 'TypeError');
test('a const array can be pushed to', branches, ['Ikeja', 'Yaba']);
test('const freezes nothing', Object.isFrozen(account), false);
test('Object.freeze is what stops a write, and in strict mode it throws', frozenWrite, 'TypeError');
test('so the frozen value is unchanged', card.tier, 'gold');
test('const in a classic for header dies on the first increment', constInAClassicLoop, 'TypeError');
const is about the arrow, not the box. account.balanceNgn += 5000 never touches the binding, so it is legal; account = {} does, so it is not. Reach for const by default anyway — the guarantee that a name still means what it meant twenty lines ago is worth more than the ability to reassign.
The strict-mode detail matters. Outside strict mode the write to card.tier would fail silently, which is far worse than throwing. Every panel in this course is strict, and so is every ES module, so the throwing version is the one you will actually meet.