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

131
Views
Why don't JavaScript properties update automatically?

I have an object with a property that stores the checked property of a checkbox like so:

var x = {
  isChecked: document.querySelector("input").checked
};


function getX() {
  (x.isChecked ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>

When checking and unchecking the checkbox, the isChecked property's value doesn't update. Why might that be?

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

0

Since .checked is a boolean, not an object, when you say isChecked: document.querySelector("input").checked, you're just setting isChecked to the current value of element.checked. Make isChecked a function to get the actual value every time you need it.

var x = {
  isChecked: () => document.querySelector("input").checked
};


function getX() {
  (x.isChecked() ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>

Alternatively, if you want to continue using it with isChecked and not isChecked(), and you want to be able to set it manually with that variable, you can use getters and setters like this:

var x = {
  get isChecked() {
    return document.querySelector("input").checked;
  },
  
  set isChecked(checked) {
    return document.querySelector("input").checked = checked;
  }
};


function getX() {
  (x.isChecked ? console.log("checkbox is checked") : console.log("checkbox is not checked"));
}
<input type="checkbox">
<button onclick="getX()">is the checkbox checked?</button>
<button onclick="x.isChecked = false">uncheck</button>
<button onclick="x.isChecked = true">check</button>

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!