Freezing Tuple-Like Data With Object.freeze()

The provisional table now lives on a copy, so the confirmed one stays safe. Some of Nadia’s data must never change at all, though. The points for a win, a draw, and a loss sit in a tuple, POINTS = (3, 1, 0), and so does the list of teams fixed at the season’s draw.

JavaScript has no tuple type. An array or an object does a tuple’s work, but either one accepts writes by default. In this lesson, you’ll make league data read-only with Object.freeze() and see what it does to the array you hand it.

Lock the Points With Object.freeze()

In Python, a line that tries to make a win worth two points stops the script:

Language: Python
POINTS = (3, 1, 0)
POINTS[0] = 2

Python raises TypeError: 'tuple' object does not support item assignment. In JavaScript, Object.freeze() gives the same protection by making the array read-only, so nothing can overwrite, add, or remove items:

Language: JavaScript
const POINTS = Object.freeze([3, 1, 0]);
POINTS[0] = 2;
console.log(POINTS);

Run it as a file in the league-table/ folder, and JavaScript stops at the write. Here’s its error line, with the rest of Node’s output cut:

Language: Program Output
TypeError: Cannot assign to read only property '0' of object '[object Array]'
...

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.