Statements in and out of function

I would like to ask, because I had this understanding when I was learning before that the declaration of var is a global variable outside function, which is generally written outside it for easy calling.
but encountered this example to get the declaration of ID needs to be written in the function, written outside the function, then the code cannot be executed.

var inp1=document.getElementById("inp1").value,
    inp2=document.getElementById("inp2").value,
    btn=document.getElementById("btn");

I really don"t know why.

<body>

<input type="text" id="inp1">

<input type="text" id="inp2"> <button id="btn">+</button> <script> btn.onclick=function(){ var inp1=document.getElementById("inp1").value, inp2=document.getElementById("inp2").value, btn=document.getElementById("btn"); if(isNaN(inp1)==false && isNaN(inp2)==false){ var a=parseInt(inp1); var b=parseInt(inp2); var c=a+b; alert(c); }else{ alert("no"); } };</script> </body>
Mar.02,2021

mvvm framework is used too much. If written outside the callback function, the values of inp1 and inp2 are not updated in real time, so it is always an empty string.


I really don't know why

you print the value of inp1 , inp2 and you will know why

Menu