Skip to content

JavaScript private properties

  • by

There is no reserved keyword for private. A private access modifier is the principle of object-oriented programming to make properties and methods only accessible inside the declared class.

You can use it as a variable and Closures Or ES6 Classes in JavaScript

JavaScript private properties

simple example code use closure() to Create Private Properties in JavaScript.

<!DOCTYPE html>

   (function one() {
    var a = 'Hello World Private ';

    // The scope of the outer function is accessible to this inner function.
    (function two() {



JavaScript private properties

Use ES6 Classes to Create Private Properties in JavaScript.

Put the new properties within a class function Object() { [native code] }. We can utilize the getters and setters to access the hidden properties rather than attaching them to the object.

class Person {
    constructor(name) {
        var _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }

Latest ECMAScript

class Something {

        this.#property = "test";

    #privateMethod() {
        return 'hello world';

    getPrivateMessage() {
        return this.#property;

const instance = new Something();
console.log(; // It will show "undefined"
console.log(instance.privateMethod); // This will show "undefined"
console.log(instance.getPrivateMessage()); // This will show "test"

To access the public property from private property, use self.

var PersonModule = (function(){
    var self = {};

    var privateChangeNameToBob = function(){ = "World";

    self.sayHello = function(){
        console.log("Hello " +;

    self.changeName = function(){
    }; = "";

    return self;
})(); = 'Test';


Do comment if you have any doubts or suggestions on this Js private topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *