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

258
Views
Getters vs functions for internal properties

Consider this code snippet

class A {
  constructor() {
   this._val = 5;
  }
  
  get val() {
    return this._val;
  }
  
  getVal() {
    return this._val;
  }
}

const a = new A();
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);
  

Obtaining _val of object a works via both the accessor get val() as well as the regular method getVal(). Are there any differences between the two other than that the former exposes a property val on a whereas getVal() is function that is exposed as a property on a? Would there be any performance/ coding guideline considerations on when to adopt one over the other?

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

0

Take a look at the difference:

class A {
  constructor() {
   this._val = 5;
  }
  
  get val() {
    return this._val;
  }
  
  getVal() {
    return this._val;
  }
}

const a = new A();
console.log(a);
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);

class B {
  constructor() {
   this._val = 6;
  }
  
  getVal() {
    return this._val;
  }
}

const b = new B();
console.log(b);
console.log(`B.val: ${b.val}, B.getVal: ${b.getVal()}`);
  

You'll notice that get exposes _val directly as a property. The function is a function that accesses _val. That's really the only difference. Use get if you just want the property to be accessible. Use the function is you want to do stuff the variable before making it accessible, like, formatting a date, for example.

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!