8

Given

const localName = "local_name";
delete localName; // true
console.log(localName); // "local_name"

Is it possible to delete a variable declared using const?

guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    Nö its not possible do delete or redefine a constant inside the constants scope – cyr_x Feb 23 '17 at 19:02
  • 3
    From https://stackoverflow.com/questions/1596782/how-to-unset-a-javascript-variable: *"The point is the `delete` operator removes a property from an object. It cannot remove a variable."* So the answer is no (independently of whether `const`, `var` or `let` was used). – Felix Kling Feb 23 '17 at 19:02
  • 1
    http://perfectionkills.com/understanding-delete/ – Bergi Oct 11 '17 at 17:17

1 Answers1

9

delete is used to delete properties from an object.

delete foo;

will try to delete the property foo from the global object. Declared variables can never be removed with delete (no matter if you use const, let or var), and there is no other way to remove a "variable" (binding) (see @T.J.'s comment for some more details).

Related: How to unset a JavaScript variable?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    (I know *you* know this, but for lurkers...) Amusingly, the *reason* you can't delete a `const`, `let`, or `class` from global scope with `delete` is different from the reason you can't delete a `var` from global scope, although the underlying motivation for the spec decision is largely the same (I suspect). But since you can't `delete` either... :-) You can't use `delete` to remove a `const`, `let`, or `class` from the global object because they aren't *on* the global object in the first place! (Whereas a global `var` is, but it's not deleteable.) – T.J. Crowder Feb 23 '17 at 19:08
  • Yeah, my assumption was that even if `const` et al was added to the global object, it wouldn't be allowed, just like with `var`. – Felix Kling Feb 23 '17 at 19:09
  • @FelixKling Is conclusion that `const` variable declared cannot be changed whatsoever? – guest271314 Feb 23 '17 at 19:11
  • 1
    @guest271314: That's why it's `const` :) – Felix Kling Feb 23 '17 at 19:11
  • @FelixKling Is there no workaround for the behaviour? – guest271314 Feb 23 '17 at 19:13
  • @guest271314: Besides *shadowing* the constant I don't think there is. – Felix Kling Feb 23 '17 at 19:14
  • What is _shadowing_? Realms? – guest271314 Feb 23 '17 at 19:14
  • 1
    @guest271314: Just scope: `const foo = 42; (function() { const foo = null; console.log(foo); }());`. – Felix Kling Feb 23 '17 at 19:15