The difference between JS global variables and function scope variables

I was dumbfounded by such a group of questions:

var var01 = 1;
function funtest() {
 document.write(var01);
 var var01 = 0;
} 
funtest();
//:undefined
////////////////////////
var var01 = 1;
function funtest() {
 document.write(var01);
 var01 = 0;
} 
funtest();
//:1
////////////////////////
 var01 = 1;
function funtest() {
 document.write(var01);
 var var01 = 0;
}
funtest();
//:undefined
/////////////////////
var01 = 1;
function funtest() {
 document.write(var01);
 var01 = 0;
}
funtest();
//:1

is different from my understanding. Ask the boss to explain

.
May.22,2021

you didn't say how you understood it.
these are relatively basic knowledge. Landlords can read books first, such as js elevation, and they will naturally understand.
two concepts: scope chain and declaration promotion. Take the first example as an example:

var var01 = 1;
function funtest() {
 document.write(var01);
 var var01 = 0;
} 
funtest();

when creating the scope of the funtest function, the variable var01 declared by var is promoted to the top of the scope, and declaration and assignment are two processes:
code becomes:

var var01;
document.write(var01);
var01 = 1;

Let's talk about the scope chain. When we read the variable var01, we trace back up the scope chain step by step. We already have the variable var01 in the scope of the function. Well, the backtracking has stopped looking for it. When printing, it hasn't been assigned yet, so undefined


////////////////////////
var var01 = 1;
function funtest() {
 document.write(var01);
 var01 = 0;
} 
funtest();
//:1

if the variable declared inside the function does not write var, this variable will be a global variable, var01 = 0; is equivalent to changing the value of var01 outside the function.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1eb0788-5d0f6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1eb0788-5d0f6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?