Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 360
Laxmikant Dange Avatar asked Jul 08 '15 11:07

Laxmikant Dange


People also ask

How do we declare a constant in ES6 JavaScript?

ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.

How do you make a variable unchangeable in JavaScript?

If you want our variables to be truly immutable, feel free to use tools like Object. freeze() , which would make the object immutable (or array — in fact array IS the object in JS).

How do I unset a variable in typescript?

The correct way to "unset" is to simply set the variable to null .

What is a JavaScript constant?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).


3 Answers

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.

like image 200
Toni Leigh Avatar answered Sep 29 '22 12:09

Toni Leigh


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.

like image 43
Felix Kling Avatar answered Sep 29 '22 14:09

Felix Kling


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;
like image 25
Roumelis George Avatar answered Sep 29 '22 14:09

Roumelis George