How to Make Class Methods Private in JavaScript?

Find out how to create private JavaScript class instance methods

Starting with ES13/ES2022, you can mark any class method as private by prefixing the method name with # (hash symbol).

For example:

// ES13+
class Foo {
    #privateMethod() {
        return 'foobar';

const foo = new Foo();

// SyntaxError

Similarly, you can make getter, setter, generator, async, or async generator methods private as well:

// ES13+
class MyClass {
    #privateMethod() {}
    * #privateGeneratorMethod() {}

    async #privateAsyncMethod() {}
    async * #privateAsyncGeneratorMethod() {}

    get #privateGetter() {}
    set #privateSetter(value) {}

In addition to declaring methods as private, you can also:

Hope you found this post useful. It was published . Please show your love and support by sharing this post.