Today I Learned

hashrocket A Hashrocket project

Javascript Privates

You can utilize 'private' features in a javascript class via the # character prepending a name. They are referred to as 'hash names'.

These private fields must be declared ahead of time otherwise they will result in a syntax error.

For this example I replaced some declaratively 'private' attributes _closed & _balance with actual 'private' attributes #closed & #balance.

export class BankAccount {
  #closed
  #balance
  
  set balance(amount) {
    return this.#balance = amount;
  }

  get opened() {
    return !this.closed;
  }

  get closed() {
    return this.#closed == true;
  }
}

It appears that if you're at Node 12 or higher you can use this functionality.

You can read more about this at MDN

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.