Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda