Js variable scope

 function test(){
    var name = "dabao";
    console.log(name);
 }
test();
console.log(name);


 function demo(){
    var age= "dabao";
    console.log(age);
 }
demo();
console.log(age);

when I enter the breakpoint, enter name to print out dabao in the browser, and after the breakpoint ends, the table name function has been executed. Is there any operating mechanism in the input name output "
, or because the variables inside the function cannot be accessed outside the function? I know the result. I just want to know the principle.

add a question, why do the above two pieces of code have the same logic, but get different results?

Apr.27,2021

what you are confused about is that the outer print name is an empty string, because name is a window attribute, you can output window.name in the console, of course, if you change the variables inside, you must have made a mistake.


the local variable data inside the function is not accessible outside the function


debugger, the current scope of console is indeed the local scope within the function (which is also the reason why it is feasible to right-click evaluate in console at the breakpoint), so you can access name. After the debugger is passed, the console scope is global, and name is the attribute that comes with the window.name browser. If you change the name to something else, you will make a mistake.


name top seems to be the name that comes with window can be modified, but the type is fixed as string,top does not seem to be modified, these two generally can not declare variables

Menu