0

Newbie question:

Can const objects be deleted or overwritten in js?

const a = function myFunc(){}; // some code to delete 'a' and 'myFunc()' here.
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
davidLeak
  • 101
  • 2
  • 7

1 Answers1

2

A downside to using const is that you cannot clear the variable at will (const prevents it from being changed in any way).

If the variable is not in the global scope, then the garbage collector will take care of it when it goes out of scope. If it is in the global scope, then you cannot get rid of it. The work-around is to stop using const for variables that you wish to modify.

Properties of an object, assigned to a const variable are not affected by the const declaration as the const delcaration affects the variable, not the the contents that it points to. You can use Object.freeze() or Object.seal() if you want to affect properties of an object.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • thank you, that was helpful. I understand now. – davidLeak Aug 15 '15 at 22:35
  • follow up question. Does that also include it's properties and methods? may I modify those? – davidLeak Aug 15 '15 at 22:36
  • @davidLeak - it takes minutes to just try this stuff yourself. In the current version of Chrome, `const` does not prevent the assigning of properties to an object pointed to by a variable declared with `const`. It just prevents the assignment to the variable itself. This is probably because the object isn't const, just the variable. `Object.freeze()` and `Object.seal()` affect the properties of an object. – jfriend00 Aug 15 '15 at 22:44
  • If I tried it myself, I wouldn't have just learned about Object.freeze() and Object.seal(). :) Thanks again. – davidLeak Aug 15 '15 at 22:57
  • fyi - const a = {}; var b = new a; a = 33; I just changed the const 'a' back to a var. – davidLeak Aug 27 '15 at 07:06
  • @davidLeak - When I try those three statements in Chrome, I just see the second one throw an error because `a` is not a function and the third one never executes and `a` is not changed. I'm not sure what you were showing there? – jfriend00 Aug 27 '15 at 07:43
  • const work = {}; var dd = work; dd = 99; work = 22; it returns 22 and should return what ever you set it to however it's default will be an undefined object. – davidLeak Aug 27 '15 at 07:57
  • @davidLeak - What does that show? Please describe your comments rather than just posting some code. If you're typing this into the console, you are being misled as the console is reporting something other than the value of `work`. When I run that code in a jsFiddle, the value of `work` is not modified in any way. I would appreciate it if you make sure you've actually discovered something of consequence for `const` before sending me off testing something again. – jfriend00 Aug 27 '15 at 08:19