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

132
Visualizações
Accessing property in an object

Consider this code snippet

class A {
  constructor() {
    this._elem = 5;
  }

  get elem() {
    return this._elem;
  }
}

class B {
  constructor() {
    this._elem = 6;
  }
}

class C extends A {
  constructor() {
    super();
  }
}

class D {
  constructor() {}
}

const a = new A();
const b = new B();
const c = new C();
const d = new D();

function foo(obj, name) {
  const val = 'elem' in obj ? obj.elem : 42;
  const val2 = obj.elem ? obj.elem : 42;
  console.log(`For ${name} val: ${val}, val2: ${val2}`);
}

foo(a, 'a');
foo(b, 'b');
foo(c, 'c');
foo(d, 'd');

I was trying to figure out if there ever could be a case where directly using obj.elem when the property elem doesn't exist on obj could lead to incorrect logic vis-à-vis doing a check for "elem" in obj and access it only if it exists and use the value. It seems like val and val2 would always be the same. Are both equivalent?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

No, they are not equivalent, and this is because obj.elem ? obj.elem : 42 will execute the getter and see if its return value is truthy or falsy. If it happens to be falsy, then this expression will evaluate to 42. Yet, "elem" in obj is true independent on whether the method would return a falsy or truthy value.

Unrelated, but it is also not efficient, as obj.elem ? obj.elem : 42 will execute the getter twice when it returns a truthy value.

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