1. Variable domain
js only has function scope (local scope) and global scope (global scope), no block-level scope
2. Variable promotion
For variables defined by val and function a(){} , there is variable promotion.
Note: There is no variable promotion for function expressions.
Example 1:
(function() {
console.log(testc); //print out undefined
testa(); // 打印出testa testb(); // 报错:提示undefined is not a function function testa() { console.log("testa"); } var testb = function() { console.log("tesb"); } var testc = "testc";})(); Example two:
var a = 1; function b() { console.log(a); //function a(){} a = 10; console.log(a); //10, the variable a is defined in the function scope. return; function a() { //The variable is promoted to the front, which is equivalent to var a=function(){} } } b(); console.log(a); // 1, access to global variables
Example three:
var a = 1; function b() { console.log(a); //1, at this time a is a global variable a = 10; console.log(a); //10, changed the value of the global variable return; function c() { } } b(); console.log(a); //10
Corrections are welcome!