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

141
Views
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 answers
Answer question

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 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!