Differences between var and var when defining variables in javascript, javascriptvar
Let's take a look at a piece of code.
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.
Question about defining variables in js: What is the difference between the var keyword and the non-var keyword when defining variables?
There is no difference outside the method. In the method, there is no default global variable, and the scope is only in this method.
For example
<Script> var a = 1; B = 2; function a () {c = 3; var d = 4;} alert (a); alert (B ); alert (c); alert (d); // This will report an error because it is not a global variable </script>
Can javascript variables be defined with or without var? Can I assign values or not assign values? So I can call a letter at any time as a variable?
A letter can be called as a variable at any time, but the first call implicitly declares var. In special cases, we still need to define var. For example, to define a variable that is not assigned a value (only declare this variable, and this variable is not assigned a value .)