Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object.freeze not working on URL searchParams.set()

Is there a way to force an object to be recreated/cloned in order for it to be used specifically on the URL object?

I have tried using Object.freeze(new URL('http://example.com)), however, I can still add and remove searchParams to the object through url.searchParams.set('a', 'b').

I was expecting at least one of these to throw errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// Using freeze()
const url = Object.freeze(new URL('http://example.com'))
url.searchParams.set('a', 'b')
console.log(url.toString())

// Using seal()
const url2 = Object.seal(new URL('http://example2.com'))
url2.searchParams.set('c', 'd')
console.log(url2.toString())

// Also freezing the searchParams
const url3 = Object.freeze(new URL('http://example3.com'))
Object.freeze(url3.searchParams)
url3.searchParams.set('e', 'f')
console.log(url3.toString())

I would like to have a way where an error is thrown if the frozen object is used instead of cloned.

>Solution :

There are two potential things tripping you up here:

Firstly, freezing an object doesn’t freeze its sub-objects. It is not recursive. There are many implementations of a ‘deep freeze’ function that does work recursively, MDN’s documentation on Object.freeze features one. This may or may not work on built-in types, where some properties are read-only (for example, you cannot execute url.searchParams = <new value>, this raises an error, which will probably break many implementations).

Secondly, setting or altering frozen objects doesn’t raise an error unless you’re in strict mode. Otherwise, the set just silently fails.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading