Tag Archives: Object.defineProperty

Read Only Variables in Javascript

It is not recommended to define variables in the global scope.

However, if you need to, you should prevent the scenario that another developer (or you someplace else in your code) will override it.

If you don’t have to support old browsers, use Object.defineProperty:

Object.defineProperty(window,”e5Var”,{value: 1, writeable: false});
e5Var = 2;
console.log(e5Var); //1

Still, if someone redeclares the variable further in the code using “var” it will not work.

Object.defineProperty(window,”e5Var”,{value: 1, writeable: false});
var e5Var = 2;
console.log(e5Var); //2