JavaScript Variables
JavaScript Variable type is not defined. Names begin with upper or lower case A through Z and the"_" character. The remaining characters may consist of the same characters it may begin with and digits 0 through 9. Types of variables include:
- Integers - Can be expressed in decimal, octal, or hexadecimal form. When led by a 0x with characters from 0-9, and a-f, the value is hexadecimal such as "0x24". The equivalent octal value is 044 and decimal is 36.
- Floating point - Examples are 3.14, -3.14, 314e-2
- Boolean values (true or false).
- String values - May be enclosed by single ' or double " quotes. The \' or \"sequence of characters will insert a quote character into a string.
- Arrays of any of the above types.
- Objects.
There is also a NULL value which can be any of the types above, exclusive of arrays and objects. the type if the variable is determined at its creation time, by the type of variable assigned to it. Therefore the example:
var firstvar=3
creates an integer variable. If the variable value is later changed to:
firstvar="Three"
It becomes a string. Note here that when the variable is created, the keyword "var" is used to create it. When referencing the variable, after its creation, or changing its value, the keyword "var" is not used.
Variable evaluation
When evaluating expressions, variable types are favored in the following order:
- Strings
- Floating point
- Integer
- Boolean
|
|
Type Conversion Functions
Arrays
They must be declared before use with a statement like Name = new Array(length) or Name = new Array().
Example declaration:
Tree = new Array(4);
Example use:
Tree[0] = "Roots"
Tree[1] = "Trunk"
Tree[2] = "Branches"
Tree[3] = "Leaves"
The same array can also be declared at the same time values are assigned as follows:
Tree = new Array('Roots', 'Trunk', 'Branches', 'Leaves')
As new elements are added to arrays, they are automatically expanded. For instance the line:
Tree[5] = "Twigs"
Will make the array be 6 elements long. The values in the array can be of mixed types for instance it is legal to do the following:
Tree[4] = 1
Arrays may be nested as follows:
Tree = new Array('Roots', new Array('Trunk', 'Branches', 'Leaves'))
The following line:
document.write(Tree[1][2])
will print "Leaves".
Objects
Objects contain functions and data. The functions may be used to read or modify the contents of the objects public or private data. Private data is internal data that may help control characteristics or attributes of the object which cannot be modified directly from outside the object. This is why functions may be provided to allow these values to be modified within legal bounds. This manner of allowing data access can check value changes before they are implemented and prevent program errors or security violations. An array is an object in JavaScript and the following functions are contained within it:
- propertyName
- length - Example: Tree.length
|