It is not safe to omit var when defining variables, but it is legal. The scope of the defined variable depends on the location of the definition. 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 this variable. The bug will destroy you ." Run it on the browser. What is the result? Perfect run! Next, let's take a look at what's going on. There is a difference between var and variables without var definitions.
1. No var
In short, it is not safe to omit var when defining a variable, but it is legal. At this time, no matter where the variable is defined, the interpreter will assign the variable a global scope.
2. var
Safe and valid. The scope of the defined variable depends on the location of the definition. For details about the scope, see the article "javascript scope" in this blog.
In this way, the problem at the beginning can be solved. In the function, abc is defined, but the value is undefined. At this time, abc has a global scope. Outside the function, only the value of abc is updated.