Let's look at a piece of code first
function show(){ alert(abc); } var abc="defg"; show();People who have experience in C++ or Java programming may say: "This program is dead, and the variable is defined after the function that references the variable. The bug will destroy you." If you run it in the browser, what will happen? Perfectly run! Next, let's talk about what's going on - the difference between variables with var and without var definition.
1. No var
To put it simply, it is not safe to omit var when defining variables, but it is legal. At this time, no matter where the variable is defined, the interpreter will assign the variable global scope.
2. Have var
Safe and legal. The scope of a defined variable depends on the location of the defined. As for what the scope is, please refer to the article "javascript scope" in this blog.
In this way, the problem at the beginning can be solved. The definition of abc in the function is just the value of undefined. At this time, abc has a global scope, and the outside of the function is only the update of the value of abc.