Laxmikant Dange
Laxmikant Dange

Reputation: 7688

How to unset a Javascript Constant in ES6?

I read this post, using delete keyword, we can delete JavaScript variable. But when I tried the same operations with constant but it is returning false when I try to delete constant. Is there any way to delete constants from memory? I tried this answer but its also not working.

Upvotes: 64

Views: 82271

Answers (4)

Sydney C.
Sydney C.

Reputation: 978

Would this piece of code work or is it counterproductive?


export default function freeObject(object) {
  const keys = Object.keys(object)
  for (const key of keys) {
    delete object[key]
  }
}

Upvotes: 3

Toni Leigh
Toni Leigh

Reputation: 4971

You can't directly do it, looking at the specs show us that the value can be set, but not over-written (such is the standard definition of a constant), however there are a couple of somewhat hacky ways of unsetting constant values.

Using scope

const is scoped. By defining the constant in a block it will only exist for this block.

Setting an object and unsetting keys

By defining const obj = { /* keys */ } we define a value obj that is constant, but we can still treat the keys like any other variable, as is demonstrated by the examples in the MDN article. One could unset a key by setting it to null.

If it's memory management that is the concern then both these techniques will help.

Upvotes: 45

Felix Kling
Felix Kling

Reputation: 816442

The delete operator is actually for deleting an object property, not a variable. In fact, in strict mode, delete foo is a syntax error.

Usually you can "delete" a value/object by removing all references to it, e.g. assigning null to a variable.

However, since constants are not writable (by definition) there is no way to do this.

Upvotes: 36

Roumelis George
Roumelis George

Reputation: 6746

As I wrote on my comment, delete can only be used on objects and arrays. So, what you can actually do is store all your constants in a constant object and free up memory by deleting it's properties, like this:

const myConstants = {};
myConstants.height = 100;

delete myConstants.height;

Upvotes: 12

Related Questions