TC39 proposal: Record and Tuples, the real immutable data structures in JavaScript.

Alberto de Murga
3 min readApr 26, 2021
const record = #{ prop: 1}; const tuple = #[1, 2, 3]
Records and tuples

One of the misleading use cases for beginners in JavaScript is to create constant arrays and objects. With the introductions of ES6, we got two new declarators: let, for mutable variables, and const, for constants. Many beginners believe that this will make their objects and array immutable, to discover later that they are not. The object or array itself is immutable, but not their content. So far, we have relied on the method Object.freeze to deal with this use case.

// This is supposed to be immutable, isn't it?
const obj = { a: 1 }
obj.a = 2
console.assert(obj.a === 1, 'wtf')
// Assertion failed: wtf

Introducing Record and Tuples.

Records are immutable arrays. Tuples are immutable objects. They are compatible with Object and Array methods. Essentially, you can drop a Tuple or a Record in any method that takes an object, or an array and it will behave as expected, unless this implies to modify the element. This applies to method of the standard library, iterators, etc.

// Record
const record = #{ x: 1, y: 2 }
// Tuple
const tuple = #[1, 2, 3, 4]
// We can use most of the methods that work with Arrays and Objects.
console.assert(tuple.includes(1) === true, 'OK, it will not print')
// Although they will return tuples and records.
console.assert(Object.keys(record) === #['x', 'y'], 'OK, it will not print')
// Iterators work too
for (const element of tuple) {
// 1
// 2
// 3
// 4
// And you can nest them!
const nested = #{
a: 1,
b: 2,
c: #[1, 2, 3]
// Nope => doSomething(x));
// TypeError: Callback to may only return primitives, Records or Tuples

// This is ok
Array.from(tuple).map(x => doSomething(x))

However, with great power comes great responsibility.

The power

  • Comparison by value: Like other simple primitive types, they are compared by value, not by identity. Objects and arrays are equal if they are the same entity. Tuples and records are equal if they contain…
Alberto de Murga

Software engineer at @bookingcom. I like to make things, and write about what I learn. I am interested in Linux, git, JavaScript and Go, in no particular order.