Day 3 of Elm- Records
Eke Enyinnaya Diala
Posted on August 4, 2022
Records
According to Richard Feldman,
Records are plain, immutable data.
They are syntactically similar to Javascript objects but not exactly the same. They have no prototype
and no this
for example. What I really want to talk about is record updates.
Record update simply refers to how we mutate the properties of a record in Elm. The term "mutate" here is sort of a misnomer. A record update does not mutate the old record, they instead create new records based off of the old record. For example, we have this bit of elm code:
record = { a = 1, b = 2 }
newRecord = { record | a = 5 }
The code above does not mutate record
. It looks a lot like the .
operator for mutating objects in Javascript but it is not the same. This is a lot closer to spreading
record
into newRecord
and updating the fields you need. The way I think about this behaviour is along these lines in Javascript:
const record = Object.freeze({ a: 1, b: 2 });
const newRecord = Object.freeze({ ...record, a: 5 });
We are using Object.freeze
here because we need the objects returned in both cases to be immutable. You see that in both cases, no actual mutation does happen. This is good because it saves us a lot of trouble with side effects resulting from passing values by reference.
This is very very interesting!
Posted on August 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.