In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
|Think of variables as containers for storing data.|
Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume).
When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
However, you can also assign a value to the variable when you declare it:
In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":
|It's a good programming practice to declare all the variables you will need, in one place, at the beginning of your code.|
You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:
Your declaration can also span multiple lines:
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
The value of the variable carname will still have the value "Volvo" after the execution of the following two statements:
Your message has been sent to W3Schools.