Home >Web Front-end >JS Tutorial >Do JavaScript variables need to be declared?
In non-strict mode, JavaScript allows direct assignment of variables without declaring them. This is because the JavaScript interpreter can automatically declare variables implicitly. In strict mode, variables must be declared before they can be used.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
A variable is equivalent to a container, and its value is equivalent to what is contained in the container. The variable name is the label attached to the container. The variable can be found through the label so that the value it stores can be read and written.
Do JavaScript variables need to be declared?
In strict mode, variables must be declared before they can be used.
In non-strict mode, JavaScript allows direct assignment of variables without declaring them. This is because the JavaScript interpreter can automatically declare variables implicitly. Implicitly declared variables are always used as global variables.
Declaring variables
In JavaScript, declare variables using the var statement.
Example 1
In a var statement, you can declare one or more variables, or assign values to variables. Unassigned variables are initialized to undefined (undefined) values. When declaring multiple variables, they should be separated using the comma operator.
var a; //声明一个变量 var a,b,c; //声明多个变量 var b = 1; //声明并赋值 document.write(a); //返回 undefined document.write(b); //返回 1
Example 2
In JavaScript, you can declare the same variable repeatedly, or you can initialize the value of the variable repeatedly.
var a = 1; var a = 2; var a = 3; document.write(a); //返回 3
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of Do JavaScript variables need to be declared?. For more information, please follow other related articles on the PHP Chinese website!