1

I have a special case to use javascript. There is a variable defined by var myVar=xxx. Then I want to protect this variable to be changed by other code. I know that I can define the variable with const at beginning but there is some reason I can't do that. So I am looking for a way to convert an existed variable to be a const variable. Not sure whether it is possible.

1
  • 2
    You cannot. ........ Commented Mar 15, 2017 at 23:26

3 Answers 3

2

You cannot change your var into a const, but assuming that myVar is defined on the global object you can make the binding final using Object.defineProperty:

var myVar = 'sacred-value'

Object.defineProperty(window, 'myVar', {
  writable: false,
  value: window.myVar
})

myVar = 'evil-value'

console.log(myVar) //=> 'sacred-value'

Note: I have assumed the window object is your global context here, but if you are executing in a non-browser environment you may need to use global instead.

Sign up to request clarification or add additional context in comments.

4 Comments

No, var-declared global properties are already nonconfigurable
(…unless they were created by eval)
Could you explain to me what incorrect assumptions I made in more detail? I am having trouble seeing why my snippet appears to be working correctly given your criticism.
Sorry, again I was thrown off by the fact that even nonconfigurable properties can be reconfigured to be nonwritable. Everything's fine, this is a good solution for global variables.
0

You can't change a var into a const.

You could store your variable in an object, mutate it, and then freeze the object with Object.freeze to prevent further mutations:

const variables = {
  a: 'b'
};

variables.a = 'c';
Object.freeze(variables);
variables.a = 'd'; // does nothing
console.log(variables.a);

2 Comments

I tried to freeze the variable directly but it doesn't help. Is Object.freeze not working for a single variable?
Object.freeze makes objects immutable. It doesn't affect variable binding, so it won't work for your use-case without storing your variable in an object.
0

You cannot change the type of a variable declaration afterwards. However, you can introduce a new scope where you declare it as a constant:

var myVar = "xxx"; // assuming global scope

{
    const myVar = window.myVar; // or `this.` or `global.` depending on your environment
    … // your code here that will throw on assigning to `myVar`
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.