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.
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 = …;