Javascript - Variables
Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.
Note: When you assign a text value to a variable, use quotes around the value.
If you assign values to variables that have not yet been declared, the variables will automatically be declared.
These statements:
have the same effect as:
var x=5;
var carname="Volvo";
If you redeclare a JavaScript variable, it will not lose its original value.
After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.
As with algebra, you can do arithmetic operations with JavaScript variables:
You will learn more about the operators that can be used in the next chapter of this tutorial.