May 06, 2021 JavaScript
5. Declare (create) JavaScript variables
6. One statement, multiple variables
A variable is a "container" for storing information.
x=5
y=6
z=x+y
In algege while using letters (such as x) to save values (such as 5).
From the above expression z-x-y, we can calculate that the value of z is 11.
In JavaScript, these letters are called variables.
You can think of variables as containers for storing data. |
As with algetory, JavaScript variables can be used to hold values (such as x-5) and expressions (such as z-x-y).
Variables can use short names (such as x and y) or better descriptive names (e.g. age, sum, totalvolume).
Both JavaScript statements and JavaScript variables are case sensitive. |
JavaScript variables can also hold other data types, such as text values (name "Bill Gates").
In JavaScript, a text like "Bill Gates" is called a string.
There are many types of JavaScript variables, but for now, we're just looking at numbers and strings.
When you assign a text value to a variable, you should surround it with double or single quotes.
Do not use quotation marks when you assign a value to a variable that is a value. If you surround a value with quotation marks, the value is treated as text.
Creating a variable in JavaScript is often referred to as a "declaration" variable.
We use var keywords to declare variables:
After the variable is declared, the variable is empty (it has no value).
To assign a value to a variable, use an equal sign:
However, you can also assign variables when they are declared:
In the following example, we create a variable named carname and assign it the value "Volvo" and then put it in the HTML paragraph of id"demo":
Tip: You can practice declaring JavaScript variables in the JavaScript programming practice section of this site.
A good programming habit is to declare the required variables uniformly at the beginning of the code. |
You can declare many variables in a statement. The statement starts with var and separates the variables with commas:
Declarations can also span multiple lines:
In computer programs, valueless variables are often declared. A variable that is not declared with a value, and its value is actually undefined.
The value of the variable carname will be undefined after the following statement has been executed:
If you re-declare a JavaScript variable, the value of the variable is not lost:
After the following two statements are executed, the value of the variable carname remains "Volvo":
You can do the calculation by using javaScript variables, using operators such as s and s:
You'll learn more about JavaScript operators later in this tutorial.
You can learn about JavaScript arithmes in the JavaScript Programming Practices section.