I don't understand why var overwrites the value of the global variable inside a function before its called.
const VAR1=3
document.onclick=()=>{
    console.log(VAR1);
    // var VAR1=2;
    console.log(VAR1);
}
When I click, this logs
3
3
as expected but if I uncomment var VAR1=2;, I get
undefined
2
instead of
3
2
Even though I wouldn't have expected it to modify the global scope.
The reason I encountered this was when I was writing a library I said LIB_VERSION=x and I can then test to see the version in the program that uses it and avoid it breaking with a random error message.
But since some old versions of the library don't have this defined I said
function testVersion(){
    if (typeof LIB_VERSION==='undefined'){
        var LIB_VERSION="Unknown Version";
    }
    if (LIB_VERSION!==3){
        console.log("Your version of the library "+LIB_VERSION+" is not compatible with this program");
    }
}
I know there are several workarounds I was curious as to why this happened.
Something else I noticed was if I put a console.log(LIB_VERSION) just before the if statement I would find that LIB_VERSION was undefined before even entering the if (so if it had something in it it gets erased).
Thanks in advance!
 
     
     
    