How to Delete a Constant in JavaScript?

Estimated read time 1 min read

In JavaScript, you cannot delete a constant once it has been declared. Constants are designed to be immutable and are not meant to be changed or deleted once they have been defined.

If you try to delete a constant using the delete operator, you will receive a SyntaxError:

const myConstant = 42;
delete myConstant; // SyntaxError: Cannot delete a constant variable

If you need to change the value of a variable, you should use a let or var declaration instead of a const declaration. If you need to ensure that a variable cannot be changed once it has been set, you can use the Object.freeze() method to freeze the object, which will prevent any changes to its properties.

const myObject = Object.freeze({
  prop1: "value1",
  prop2: "value2"
});

// Attempting to modify the object will throw an error
myObject.prop1 = "new value"; // TypeError: Cannot assign to read only property 'prop1' of object

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply