variable scope

First understand the variable scope, a variable scope is the area in the program source code where the variable is defined. Divided into global variables and local variables, global variables have global scope and are defined anywhere in the JS code. A variable declared inside a function can only be defined inside a function. It is a local variable, and the scope is local.

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
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326598829&siteId=291194637