The following contains valid Javascript code. I would like to know why the Set s can be constant even if new values are added. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

The following contains valid Javascript code. I would like to know why the Set s can be constant even if new values are added.

https://code.sololearn.com/W7W7o8Lwppeg/?ref=app

7th Sep 2019, 11:26 PM
Sonic
Sonic - avatar
7 Answers
+ 7
In this case const s value is a reference to the memory location of the set. So when you add to the set you are not changing the value stored at const s, instead you are adding/changing the set at the location that const s references/points to. Keep in mind objects are pass by reference and primitives are pass by value. https://javascript.info/object#copying-by-reference
8th Sep 2019, 12:12 AM
ODLNT
ODLNT - avatar
+ 7
Sonic I must admit I'm perplexed by the fact that Object freeze() doesn't work on Set nor Map, but it can freeze an array. Is there a way to freeze an ES6 Map? https://stackoverflow.com/questions/35747325/is-there-a-way-to-freeze-an-es6-map
8th Sep 2019, 1:53 AM
ODLNT
ODLNT - avatar
+ 5
Sonic I would look at the source code from Immutable.js to see how they do it. I've not explored why Object.freeze(set|map) doesn't lock these. I imagine freeze applies to shallow properties and the actual references are probably up the prototype chain. 🤷‍♂️
9th Sep 2019, 5:15 AM
David Carroll
David Carroll - avatar
+ 4
Thanks ODLNT . So like a const pointer in C I suppose. Is Object.freeze() what is required to make s unmodifiable in the JS code above? Edit: Object.freeze(s) does not make the code unmodifiable either.
8th Sep 2019, 12:17 AM
Sonic
Sonic - avatar
+ 3
ODLNT thanks!
8th Sep 2019, 9:29 AM
Sonic
Sonic - avatar
+ 2
Any convenient way to make a Set immutable in JS, David Carroll ?
9th Sep 2019, 4:41 AM
Sonic
Sonic - avatar
0
ok
10th Sep 2019, 11:07 AM
Roberto Fajer
Roberto Fajer - avatar