add a private property to a class in javascript

In JavaScript, there is no built-in support for private properties, but you can simulate them using symbols or underscore convention. Symbols are a new primitive type added in ECMAScript 6 that can be used as unique identifiers. Here's an example of how to create a private property using symbols:

index.tsx
const _privateProperty = Symbol('privateProperty');

class MyClass {
  constructor() {
    this[_privateProperty] = 'secret';
  }

  getPrivateProperty() {
    return this[_privateProperty];
  }
}
197 chars
12 lines

In the example above, we use a symbol _privateProperty to create a private property in the class MyClass. The property is initialized in the constructor and can only be accessed using the getPrivateProperty() method.

Alternatively, you can use the underscore prefix convention to indicate that a property or method is private:

index.tsx
class MyClass {
  constructor() {
    this._privateProperty = 'secret';
  }

  getPrivateProperty() {
    return this._privateProperty;
  }
}
142 chars
10 lines

In the example above, we use the underscore prefix to indicate that _privateProperty is a private property in the class MyClass. However, this convention is not enforced by the language, and the property can still be accessed from outside the class.

gistlibby LogSnag