Can we assign Array to the key of Record and Object in index of Tuples in Javascript?

106 views Asked by At

ES15 has introduced Records and Tuples, So can we use array as a attribute value inside the Record? Can we use object as a value of Tuple index?

1. Is it a valid for Record ?

const user = #{
  name: "Avyukt",
  age: 39,
  hobbies: ['sleeping', 'eating', 'crying'] // Is it a valid add arr 
}

2. Is it a valid Tuple?

const user = #[ 
    { name: "Avyukt", age: 1 }, // Is it valid to add object as a value
    { name: 'Reyansh', age: 5 } 
]
2

There are 2 answers

0
Adam Jenkins On

This part of the proposed specification:

https://github.com/tc39/proposal-record-tuple/blob/5c9a6e144c687ef5911f4c0c088bc21343cbaf68/README.md?plain=1#L252

Records and Tuples may only contain primitives and other Records and Tuples. Attempting to create a Record or Tuple that contains an Object (null is not an object) or a Function throws a TypeError.

No, a tuple may not contain an object, but it can contain a Record, in the current proposal

Likewise, a record may not contain an array value, but it can contain a tuple.

I would caution against the title that ES15 has introduced anything.

This is currently a stage 2 proposal only.

2
Nick Parsons On

As Adam pointed out in their answer, in the current iteration of the proposed spec you can't store objects (including arrays) in records or tuples, otherwise you'll get a TypeError. The escape hatch the spec authors suggest is the use of a Symbol with a Map. The idea is to place a Symbol in the place of your object/array within your record/tuple. The Symbol is then used as a key in a Map, allowing you to essentially dereference the symbol by looking up its corresponding value in the Map, for example:

const RefsRegistry = new WeakMap(); 
const hobbiesRef = Symbol("hobbies");

RefsRegistry.set(hobbiesRef, ['sleeping', 'eating', 'crying']); // ECMAScript 2023 (ES14) now allows for Symbols in WeakMaps

const user = #{
  name: "Avyukt",
  age: 39,
  hobbies: hobbiesRef
};

Now the above record is valid, since it no longer contains an array, but rather holds a Symbol, and as that's a primitive it's allowed.

When reading the value, you would need to dereference the Symbol using the Map, for example:

const hobbies = RefsRegistry.get(user.hobbies);