Search code examples
javascriptclassprivate-members

What does the `#` symbol (number sign) do inside a JavaScript class?


I encountered code that contained the # sign. What is it used for? The code looks something like this:

class someObject{
  #someMethod(){
    //do something 
  }
}

Solution

  • It's a sigil (rather than an operator) that indicates that the member is private — in this case, a private method, but it's also used for private fields.

    You can't use a private method or private field in code outside the class declaring them. For instance:

    class Example {
        doSomething() {
            this.#method("from doSomething"); // <== Works
        }
        #method(str) {
            console.log("method called: " + str);
        }
    }
    const e = new Example();
    e.doSomething();
    e.#method(); // <=== FAILS