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

159
Views
Private constants in JavaScript `class` syntax

I know I can create a private constant by putting it into an IIFE's closure:

let testObj = (function() {
  const myConst = 'test value';

  return {
    showPrivateConst() { 
      return myConst;
    }
  }
})();

console.log(testObj.showPrivateConst()); // test value

But I'm looking for the best way to do this using class syntax and the # private indicator. So far, the best I've come up with is this:

class Test {
  get #myConst() {
    return 'test value';
  }

  showPrivateConst() {
    return this.#myConst;
  }
}

let testObj = new Test();
console.log(testObj.showPrivateConst()); // test value

This seems kind of baroque. Is this the way to do it, setting up a read-only private property to get a private constant, or is there a more idiomatic way to do it?

Edit: I've been getting some feedback about static properties being the way to do this. I've looked at static properties as well, and they pretty much give me the same question. I can't make a private static variable a constant, so it looks like I have to make it a readonly property using a getter method. Here's the example using a static property:

class Test {
  static get #myConst() {
    return 'test value';
  }

  showPrivateConst() {
    return Test.#myConst;
  }
}

let test = new Test();
console.log(test.showPrivateConst()); // test value

So, this gives rise to pretty much the same question. It seems kind of baroque, and I'm wondering if there's a more idiomatic way to do it.

about 4 years ago · Juan Pablo Isaza
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!