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

213
Vistas
Losing the value of a variable javascript

Why am I losing the value of a variable one? I tried to declare the variable as a global variable and it didn't work. I also tried some console.log commands, but didn't understand what happened.

function check() {
  document.addEventListener("DOMContentLoaded", ready);
}
let one; // 1
function ready() {
  let button = document.getElementById("transform");
  let div = document.getElementById("objectImg");
  let img = document.getElementById("dog");

  console.log(div);
  console.log(button);
  button.addEventListener("click", function(a) {
    if (img) {
      img.parentNode.removeChild(img);
      div.innerHTML = "<img id = 'red' src = 'img/cat.jpg'>";
      one = document.getElementById("red");
      img = false;
      console.log(one); // <img id="red" src="img/cat.jpg">
    } else {

      alert("some text");
    }
  });
  console.log(one); // undefined
  //  one.addEventListener("mouseover", (a) => {
  //     });
}
check();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The reason is that you are setting the value to one inside an event listener. The code inside the event listener is executed after the button is clicked. So, set the value to one outside of the event listener

about 4 years ago · Juan Pablo Isaza Denunciar

0

In your code you are calling the one before it's initiated, so as per the below code you can call the function once the one variable is assigned with some values, then you will get value.

let one;

(function () {
  
  document.getElementById("button").addEventListener("click", function(a) {
  
    one = 56
  
    console.log('one from button click event: ' + one)
    
    callWhenOneIsSet()
    
  })
  
})()

function callWhenOneIsSet() {
  console.log('one from callWhenOneIsSet: ' + one)
}
<button id="button">Click it</button>

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