How to Make Class Fields Private in JavaScript?

Starting with ES13/ES2022, you can specify private class fields/members by prefixing the field name with # (hash symbol).

For example:

// ES13+
class Foo {
    #privateProp;

    constructor() {
        this.#privateProp = 123;
    }
}

const foo = new Foo();

// SyntaxError
console.log(foo.#privateProp);

Similarly, you can:


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.