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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s