Search code examples
javascriptvariablesglobal

Can't access global variables inside a function (Javascript)


I wrote a simple BMI calculator, but I seem to be unable to access global variables inside the function. If weight is only a number, everything is okay--but when I want to get this element with Javascript, it doesn't work. When those variables are inside a function, everything works excellent. I know, hoisting, scope.. but why do variables with numbers work then?

Here is the code:

const height = parseInt(document.querySelector("#height").value);
const weight = parseInt(document.querySelector("#weight").value);

const results = document.querySelector("#results");

function bmiCalc() {
  if (height === "" || isNaN(height))
    results.innerHTML = "Invalid Height! Please use numbers";
  else if (weight === "" || isNaN(weight))
    results.innerHTML = "Invalid Weight! Please use numbers";
  else {
    const bmi = (weight / ((height * height) / 10000)).toFixed();
    results.innerHTML = bmi;
  }
}

const button = document.querySelector(".results__btn");

button.addEventListener("click", bmiCalc);

Solution

  • that is because you are fetching the value before the user enters anything, because the input data is fetched once script starts running