Search code examples
javascriptfunctiondomevent-handlingvariable-assignment

Reassigning global variable in JavaScript - Can somebody explain to me why currentAcc stays undefined


so basically I tried the same thing in a simple test scenario without .addEventlistener() and it works but I do not get this to work, currentAcc stays undefined in the global scope and does not takes the assigned value of the function. I would much appreciate some help.

let currentAcc;

function logIn() {
  function logInCurrAcc(event) {
    event.preventDefault();

    currentAcc = accounts.find((acc) => acc.username === usernameInput.value);
    console.log(currentAcc);

    if (currentAcc.password === passwordInput.value) {
      window.location.assign("app.html");
    } else {
      alert.classList.remove("hidden");
      setTimeout(function () {
        alert.classList.add("hidden");
      }, 3000);
    }
  }

  submitFormBtn.addEventListener("click", logInCurrAcc);
}

console.log(currentAcc);

// Initializes everything
function init() {
  if (document.body.contains(tabsContainer)) {
    tabsComponent();
    sliderComponent();
    modal();
    logIn();
  } else {
    console.log("Not loading init");
  }
}

init();```

Solution

  • JavaScript interpreter doesn't enter the body of a function until it gets executed.

    This is a simplified example of how the interpreter executes your code:

    let currentAcc; // empty variable declaration
    
    function logIn() {} // function declaration, doesn't enter, only saves a pointer to it into the memory
    
    console.log(currentAcc) // undefined, because `currentAcc` is still empty
    
    function init() {} // function declaration
    
    init() // function execution, now interpreter goes into the body of `init` func and so on
    

    So according to the code you posted, currentAcc variable stays undefined until user click.

    If you need to pass data between pages, consider using window.localStorage or window.sessionStorage.

    If you need more help, please post a Minimal, Reproducible Example so I can help you with some actual code.