There are a few small knowledge points.
(1) Local variables have higher priority than global variables with the same name
var a = 'apple'//global variable |
function QQ(){ |
var a = 'apple2'// local variable with the same name |
return a; |
} |
console.log(QQ())// apple2 |
(2) Because functions can be nested, there will be several nested local variable scopes.
var a = 'apple' | |
function QQ(){ | |
var a = 'apple2'; | |
function WW(){ | |
var a = 'apple3' | //because of local variables in nested scopes |
return a; | //return the current value |
} | |
return a; | |
} | |
console.log(QQ()); | //apple2 |
The scope of the function;
the function scope in js means that all variables declared in the function are visible, which means that the variables can be used before they are declared, which is called advance declaration;
var a = 1;
function f(){
console.log (a);//It is 'undefined'
var a = 2;//The variable is assigned here, the single variable is defined in the whole function.
console.log(a);// output 2
}