A small problem with js

related codes

var a = "aa";
test ();
function test () {
console.log (a);
var a = "bb";
console.log (a);
}
console.log (a);
/ / undefined bb aa

I would like to ask why the undefined is printed in the first place. Isn"t it possible to access variables outside the function inside the function

Jun.30,2021

because you also redefine a below, an is considered to be a local variable , so when test () runs to the first console.log (a) , the value of an is undefined , and then it will be assigned to bb .

to understand the execution order of var a = 'bb' , execute var a = undefined first, and then assign bb to a until the assignment statement is executed.


to pass an as an argument to the function


you can take a look at the problem of variable promotion. If the variable is redefined within the function, the variable will also be promoted in the local environment, with a value of undefined

.
Menu