Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Cannot redefine property when trying change property of a global variable

How can we set custom getter/setter on already existing global variable? A straightforward approach fails:

var myVar;

{
  let _myVar = myVar;
  delete myVar;
  Object.defineProperty(window, "myVar", {
    get()
    {
      return _myVar;
    },
    set(val)
    {
      _myVar = val;
    }
  });
}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

var myVar;

According to this document:

Any property declared with var cannot be deleted from the global scope or from a function's scope.

Therefore, delete myVar won't get applied, and that's why you cannot set a value again for myVar with defineProperty.

For a simple test, you can try to log myVar value after delete myVar.

var myVar = 5; //set a value for `myVar`

{
  let _myVar = myVar;
  delete myVar; //delete `myVar`
  console.log(myVar); //it's still 5
  Object.defineProperty(window, "myVar", {
    get()
    {
      return _myVar;
    },
    set(val)
    {
      _myVar = val;
    }
  });
}

For a potential solution, you can explicitly set a property to window object which is considered as a global variable.

window.myVar = 5; //set a value for `window.myVar`

{
  let _myVar = window.myVar;
  delete window.myVar;
  console.log(window.myVar); //`undefined` as expected
  Object.defineProperty(window, "myVar", {
    get() {
      return _myVar;
    },
    set(val) {
      _myVar = val;
    }
  });
}

Just one side note that in terms of global variable usage, var and window are not different. You can declare window.myVar, but you can use myVar (without window) directly.

window.myVar = 5; //set a value for `window.myVar`

{
  let _myVar = myVar;
  delete window.myVar;
  console.log(window.myVar); //`undefined` as expected
  Object.defineProperty(window, "myVar", {
    get() {
      return _myVar;
    },
    set(val) {
      _myVar = val;
    }
  });
  console.log(myVar); //set it again with `defineProperty`
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!