Variables are "containers" used to store information.
Just Like Algebra
In algebra, we use letters (such as x) to store values (such as 5).
Through the above expression z=x+y, we can calculate the value of z to 11.
|You can think of variables as containers for storing data.|
Variables can use short names (such as x and y) or more descriptive names (such as age, sum, totalvolume).
Variables must start with a letter
Variables can also start with $ and _ symbols (but we don’t recommend this)
Variable names are case sensitive (y and Y are different variables)
When you assign a text value to a variable, you should surround the value with double quotes or single quotes.
When the value you assign to a variable is a numeric value, do not use quotation marks. If you surround the value with quotation marks, the value will be treated as text.
// If you are familiar with ES6, pi can use the const keyword to indicate a constant
// const pi = 3.14;
var person="John Doe";
var answer='Yes I am!';
We use the var keyword to declare variables:
After the variable is declared, the variable is empty (it has no value).
To assign a value to a variable, use the equal sign:
However, you can also assign values to variables when declaring them:
In the following example, we created a variable named carname, assigned the value "Dodge" to it, and put it in the HTML paragraph with id="demo":
|A good programming practice is to declare the required variables uniformly at the beginning of the code.|
Multiple Variables in One Statement
You can declare many variables in one statement. The statement starts with var and uses commas to separate variables:
var lastname="Doe", age=30, job="carpenter";
The statement can also span multiple lines:
Multiple variables declared in a statement cannot be assigned the same value at the same time:
x and y are undefined and z is 1.
Value = undefined
In computer programs, variables with no value are often declared. The value of a variable declared without a value is actually undefined.
After executing the following statement, the value of the variable carname is undefined:
After the following two statements are executed, the value of the variable carname is still "Volvo":
Use let and const (ES6)
Safari 10 and Edge 14 are the first browsers to support all the features of ES6:
|Chrome 58||Edge 14||Firefox 54||Safari 10||Opera 55|
|Jan 2017||Aug 2016||Mar 2017||Jul 2016||Aug 2018|