Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda