>_How to create read only property in JavaScript?

Posted 1 month ago  36 reads  

Author: Marghoob Suleman

Have you ever wonder, how to create readonly properties in JavaScript.

Well, there are multiple ways to create read-only properties in JavaScript. Let's find out.

Create readonly property in an object.

var obj = Object.defineProperty({}, "width", {
    value: 20,
    writable: false
});
console.log(obj.width); //20;
obj.width = 30; //try to change it here
console.log(obj.width); //20;

You may also create readonly property in es6 style.

var obj = {
    get width() {
        return 20;
    }
};
console.log(obj.width); //20;
obj.width = 30;
console.log(obj.width); //20;

How about creating readonly property in a javascript class? Do not create set method.

class Obj {
    static get width() {
        return 20;
    }
}
console.log(Obj.width); //20;
Obj.width = 30;
console.log(Obj.width); //20;

Or how about creating a private variable and return it. At the time of writing this article; below is not supported by Safari browser.


class Hello {
    static #world = "World!";
    hi() {
        return Hello.#world;
    }
}
var h = new Hello();
h.hi();
console.log(h.world); //undefined
console.log(h.world); //will throw an error: Private field '#world' must be declared in an enclosing class

Powered by HashtagCms.org