Introducing JavaScript Variables
Variables are a key element of just about every programming language ever invented, and just like other programming langauges, an understanding of the basics of JavaScript variables is key to learning this scripting langauge.
Variables are nothing more than a way to store information in memory. A variable can be a number, a single character, a string of characters making up a work or sentence, or a value indicating whether something is true or false. In JavaScript you declare a variable by giving it a name and assigning a value to it. You can then access this data at any time and, more importantly, change either the content of the variable whenever necessary (hence the name variable).
Variables are assigned and manipulated using operators which will be covered in a later chapter. At this stage it is important to understand one operator in particular - the assignment operator.
Variable Declaration and the Assignment Operator
Varaibles in javaScript are declared by by specifying the name name of the variable storage you wish to create prefixed with the token var. For example, to create a variable named myVariable:
var myVariable;
The above line creates a new variable which can be accessed using the name myVariable but does not assign any initial value.
Note that whilst it is also possible to declare a variable without the var token this is strongly discouraged. Failing to specify the 'var' before the variable can cause confusion when variables with the same name are present in local and global scopes. Good practice dictates that all variable declarations be prefixed with the var token.
The '=' assignment operator can subsequently be used to assign a new value to our variable:
myVariable = 10;
In this instance the variable which had already declared is asssigned the to contain an integer value of 10.
In addition, the variable can be initialized at the same time that it is declared. For example:
var myVariable = 10;
achieves the same result as the following script sequence:
var myVariable; myVariable = 10;
JavaScript Variable Naming Conventions
JavaScript variable names are made up of letter, numbers and underscores. They cannot contain spaces and must not begin with a number. For example sales_percentage would be a valid variable name, where as sales percentage would be invalid because it contains a space character. Similarly two_layers is valid, but 2_layers is not due to the fact that it begins with a number. JavaScript variable names can be of any length, although common sense should be used to ensure excessively long name are not used.