0

On running this code why x is no getting delete from this global object is delete operation not work on this(global) object?

var x = 1;
console.log(this.hasOwnProperty("x")); // browser -> true
delete this.x; // -> x should be removed from this/window object

console.log(x);

Help me to understand this

  • `delete this.x` has an effect if you delete the `var` before `x = 1`. – Heiko Theißen Jul 30 '23 at 16:19
  • How exactly are you running this in nodejs? Most likely, [`this` is not the global object](https://stackoverflow.com/q/22770299/1048572) there - or at least [`var x` is not declaring a global variable](https://stackoverflow.com/questions/34967530/about-global-variables-in-node-js). – Bergi Jul 30 '23 at 16:33
  • 1
    What is the point of `val` and that IIFE? Why not just `console.log(x)`? – Bergi Jul 30 '23 at 16:34
  • @GrafiCode So? `this.x` is a property. – Bergi Jul 30 '23 at 16:36
  • 1
    @GrafiCode No, `this.x` is referring to a property on the `this` value, which is an object here. Btw, the term "VariableObject" [is no longer used since 2011](https://stackoverflow.com/q/40544709/1048572) – Bergi Jul 30 '23 at 16:48
  • @GrafiCode That question and answer is specific to modules, not regular top-level code. – Barmar Jul 30 '23 at 17:04
  • "*why x is no getting delete from this global object*" - because you declared a `var`, which creates a non-configurable (writable, but not deletable) property. Use strict mode to get an exception from the `delete`, or look at the return value of the `delete` expression which is false. Use `Object.getOwnPropertyDescriptor(this, 'x')` to see how the property is defined. – Bergi Jul 31 '23 at 17:20
  • …and see https://stackoverflow.com/questions/1596782/how-can-i-unset-a-javascript-variable for more explanation, as well as how to create a global property that can be deleted successfully – Bergi Jul 31 '23 at 17:21

0 Answers0