0

I'm a beginner in js and while experimenting I noticed something strange in my app :

var pin = "";
var inputField = document.querySelector('.pin'); // initialize globally 


const addNum = (num)=>{
  //let  inputField = document.querySelector(".pin"); //code works by initializing this 
  pin+=num;
  inputField.value = pin; //error hits 
}

If I initialize my inputField variable globally I get the error Uncaught TypeError: Cannot set property 'value' of null in my app . However when I declare and initialize the variable in my function I get no null error and my code runs . Why does this happen if my variable is globally scoped how can it be null?

vasilis 123
  • 585
  • 1
  • 12
  • 26
  • Most likely, because the global variable code runs before the element with class "pin" has been loaded but you invoke the function afterwards. – Álvaro González Oct 27 '20 at 13:01
  • You walk into the room and yell for Bob. No one answers and you go on your way. Bob walks into the room. He has no idea you called for him. You are referencing the element before it exists. – epascarello Oct 27 '20 at 13:03

0 Answers0