Freezing Tuple-Like Data With Object.freeze()

Copies kept the confirmed table safe from the evening’s results. The points per result, POINTS = (3, 1, 0), and the teams fixed at the season’s draw shouldn’t change at all. JavaScript has no tuple type, and arrays accept writes. In this lesson, you’ll make league data read-only with Object.freeze().

Lock the Points With Object.freeze()

Object.freeze() makes an array or object read-only, so you can’t overwrite, add, or remove items. Here’s the tuple’s port, with a write Python would refuse:

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

The league-table/ directory’s package.json sets "type": "module", so its .js files run as modules in strict mode. When you run the code as a .js file in that directory, it stops at the write. Here’s the 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]'
...

It’s JavaScript’s version of Python’s TypeError: 'tuple' object does not support item assignment. The message says property '0' because an array’s items are properties named by their index. The rest maps like this:

Python tuple JavaScript frozen array
POINTS = (3, 1, 0) const POINTS = Object.freeze([3, 1, 0]);
sorted(POINTS) POINTS.toSorted((a, b) => a - b)

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.