JS Variables
JS variables are basically containers for storing information. As with Algebra in Mathematics, JS variables are used to hold values or expressions. A variable can have a short name, like “num”, or a more descriptive name, like “string”.
Rules for naming of JS variables:
- JS variable names are case sensitive (‘p’ and ‘P’ are two different variables)
- JS variable names must begin with a letter or the underscore character
N.B. As because JS is case-sensitive, variable names are also case-sensitive.
Example. A variable’s value can change during the execution of a script. We can refer to a variable by its name to display or change its value. This example will show us how to do this:
<html> <body> <script type="text/javascript"> var firstname; firstname="Sandip"; document.write(firstname); document.write("<br>"); firstname="Sandy"; document.write(firstname); </script> <p>The script above declares a variable, assigns a value to it, displays the value, change the value, and displays the value again.</p> </body> </html>
Creating JS Variables
Creating variables in JS is most often referred to as declaring variables. We can declare JS variables with the var statement:
var num; var string;
After the declaration shown above, the variables are empty (they have no values yet). However, we can also assign values to the variables when we declare them:
var num = 10; var string = "motherland";
After the execution of the statements above, the variable num will hold the value 10, and string will hold the value motherland.
N.B. When we assign a text value to a variable, use double quotes around the value.
Assigning Values to Undeclared JS Variables:
If we assign values to variables that have not yet been declared, the variables will automatically be declared. These statements are:
num = 10; string = "motherland";
have the same effect as:
var num = 10; var string = "motherland";
Re-declaring JS Variables:
If we re-declare a JS variable, it will not lose its actual value.
var num = 10; var num;
After the execution of the JS statements above, the variable num will still have the value of 10. The value of num is not reset when we re-declare it.
JS Arithmetic:
Like algebra in mathematics, we can also perform arithmetic operations with JS variables:
b = a - 10;
c = b + 10;