Tuples/ Records in JavaScript

296 Views Asked by At

I was referring to this link: Future Javascript: Records and Tuples and I was wondering, what is the reasoning behind these?

We can still use Object.freeze with both arrays and objects to achieve this. Only reasoning I can think of is compare by value. So this will allow us to have complex object like structure(records) in Set as keys and we can fetch them without much hassle. But does this look big enough reason to add new datatype in a language?

1

There are 1 best solutions below

2
Peter Seliger On

Object.freeze protects writing access just at an object's first (entry/property) level. Any structure nested deeper than 1 is writable. Thus a frozen object never is deeply frozen.

In order to achieve the latter one has to write ones' own recursive deepFreeze function.

In contrast the future primitive Record and Tuple values are truly/entirely immutable.

const wellTempered = {
  foo: {
    bar: 'baz',
    biz: {
      buzz: 'booz',
    },
  },
  safe: 'protected',
};
const frozen = Object.freeze(wellTempered);

console.log(
  '(wellTempered === frozen) ?..',
  (wellTempered === frozen),
);

// - level 1 is frozen, thus not writable.
// - writing attempts will fail silently
//   in non strict mode.

frozen.safe = 'vulnerable';

// - `freeze` doesn't freeze deeply.
//
// - nested levels deeper than 1
//   are still writable.

frozen.foo.bar = "fooled";
frozen.foo.biz.buzz = "doomed";

console.log({
  wellTempered,
  frozen,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }