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

How to create nested properties on a window object in one line only if they don't exist with JavaScript?

I’d like to create nested properties in the window object in one line if possible, and only if they don’t exist.

Is there a way to simply this?

window.level1        = window.level1 || {}
window.level1.level2 = window.level1.level2 || {}

windows.level1 can contain data in certain conditions, so it can’t be overwritten.

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

I tried something like the following, but it still throws Uncaught TypeError: Cannot read properties of undefined (reading 'level2')

window.level1.level2 = (window.level1 || {}).level2 || {}

Is this possible at all in one line? If so, how?
And if there is a solution it would be great if it also works on old browsers.

>Solution :

You’ll need different nesting:

((window.level1 = window.level1 || {}).level2 = window.level1.level2 || {}).level3 = …;

or using nullish assignment for short (and not writing the existing values into the property again):

((window.level1 ??= {}).level2 ??= {}).level3 = …;
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