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

135
Views
How to change object values in a function outside that object, vanilla Javascript

I am trying to change the values of an object using function outside of that object, so that I can access those values later (in yet another objects).

I am new to programming, apologies if there is something wrong in my description or question.

For instance,

let myObject = {
  startTime: '',
  endTime: '',
  newId: '',
    
  set setStartTime (val) {
    this.startTime = val
  }
}
    
stopButton.addEventListener('click', () => {
  const {startTime, endTime, newId} = myObject

  myObject.setStartTime = new Date()
    
})

console.log(myObject.startTime)

So when I console log myObject.startTime - in the console its value is empty. Apparently, because it just logs the initial (unchanged value). Why does this happen, and how can I solve this?

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

0

when I console log 'myObject.startTime' - in the console its value is empty

Because your code when it loads at first time will show the initial value of myObject which is empty. After you click on stopButton will change but not log any thing, because console.log(myObject.startTime) outside of function, Solution, put console.log inside of click of stopButton.

var dateNow = null;//declare it globally here
stopButton.addEventListener('click', () => {
  const {startTime, endTime, newId} = myObject

  myObject.setStartTime = new Date()
  dateNow = myObject.setStartTime;//<-- assign it value here
})

console.log(dateNow )//<-- call it outside of function here

if I can use that new value (generated inside a function) outside of that function?

Yes you can, just declare a variable globally (outside of function ) to hold the generated value inside click function; then you can call it outside of it.

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!