'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.

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 1:[1]

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

Solution 2:[2]

Try this approach:

window.level1 = window.level1 ? window.level1.level2 ??= {} : { level2: {} };

console.log(window.level1);
.as-console-wrapper{min-height: 100%!important; top: 0}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 A1exandr Belan