Home > Article > Web Front-end > An introductory tutorial on understanding JavaScript variables_Basic knowledge
Variables are containers used to store information:
x=5; length=66.10;
Remember algebra from school?
When you think back to the algebra courses you took in school, you probably think of: x=5, y=6, z=x y, etc.
Remember, a letter can hold a value (such as 5), and using the information above, you can calculate the value of z to be 11.
You must not have forgotten, right?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x y).
JavaScript Variables
Just like in algebra, JavaScript variables are used to hold values or expressions.
You can give the variable a short name, like x, or something more descriptive, like length.
JavaScript variables can also hold text values, such as carname="Volvo".
Rules for JavaScript variable names:
Variables are case sensitive (y and Y are two different variables)
Variables must start with a letter or underscore
Note: Since JavaScript is case-sensitive, variable names are also case-sensitive.
Example
During the execution of the script, the value of the variable can be changed. You can refer to a variable by its name to display or change its value.
This example shows you the principle.
Declare (create) JavaScript variables
Creating variables in JavaScript is often called "declaring" them.
You can declare JavaScript variables via the var statement:
var x; var carname;
After the above declaration, variables have no value, but you can assign values to variables when declaring them:
var x=5; var carname="Volvo";
Note: When assigning a text value to a variable, enclose the value in quotes.
Assigning values to JavaScript variables
Assign a value to a JavaScript variable via an assignment statement:
x=5; carname="Volvo";
The variable name is on the left side of the = symbol, and the value to be assigned to the variable is on the right side of the = symbol.
After the above statement is executed, the value saved in the variable x is 5, and the value of carname is Volvo.
Assigning a value to an undeclared JavaScript variable
If the variable you assign a value has not been declared, it will be automatically declared.
These statements:
x=5; carname="Volvo";
Has the same effect as these statements:
var x=5; var carname="Volvo";
Redeclare JavaScript variables
If you declare a JavaScript variable again, the variable does not lose its original value.
var x=5; var x;
After the above statement is executed, the value of variable x is still 5. The value of x is not reset or cleared when the variable is redeclared.
JavaScript arithmetic
Just like algebra, you can do arithmetic using JavaScript variables:
y=x-5; z=y+5;