Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 = …;
about 4 years ago · Juan Pablo Isaza Report

0

Try this approach:

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

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!