1. Simply speaking, a variable defined inside a function is a local variable, which can not be accessed outside the function; Global variables are outside the function and can be accessed both inside and outside the function;

var a = 10; function test() { var b = 100; console.log(a); A =100; } test(); console.log(a); // Prints 100 console.log(b); B is not defindCopy the code

Because a is a global variable, it can be accessed and assigned within the function; The first print is 10; The value of a becomes 100 after executing the function; B is a local variable; The value of b cannot be accessed because it is printed outside the function.

2. If the names of local variables and global variables are the same;

var a = 10; function test() { console.log(a); Undefind var a = 100; console.log(a); // Print the result as 100} test(); console.log(a); // Prints 10Copy the code

Note: 1. If the name of the local variable is identical to the name of the global variable, all the values of the local variable in the function point to the local variable; 2. Undefind in line 5; Because as long as the local variable a is declared, a refers to the local variable, but it is printed before assignment, and the result is undefind; The second print is 100 after the assignment; To change the value of the global variable a, use window.a; The global variable a, 10, is printed outside the function for the third time.

3. On the question of parameters; Parameters are also local variables;

var a = 1; function test(a) { a=100; console.log(a); // Print a result of 100 return a; } test(a); a=test(a); console.log(a); // Prints 1Copy the code

Function parameters and global variables have the same name; Since parameters are local variables, all internal operations on a point to local variable A and do not affect global variable A, so output 1; The output of 100;

The simple understanding is that the parameter refers to the value of the variable, which is processed inside the function without changing the value of the variable. (here is the value type parameter passing case can be understood as follows); If the parameter is passed by reference type; It affects the value of the global variable; (This has to do with data storage);