JavaScript tutorial - Variables

Navigation

Skip navigation.

Site search

Site navigation

JavaScript tutorial

Printing

Other tutorials

Variables

Variable types are not important in JavaScript. They may be interchanged as necessary. This means that if a variable is a string one minute, it can be an integer the next. The basic variable types are:

character
'a' or '@' or 'k' etc.
string
'hdttgs 8 -46hs () Get the idea'
integer
0 or 1 or 2 or 3 or 4 etc. or -1 or -2 or -3 or -4 etc.
float (or double)
23.546 or -10.46
boolean
true or false
function
A function; see the section on Functions
object
An object; see the section on Object oriented programming
array
A type of object that can store variables in cells (see below)
regular expression
A pattern that can be used to match strings or substrings
undefined
A variable that has not been given a value yet
null
A variable that has been defined but has been assigned the value of null

Integer and float are grouped together as 'number'. Character and string are grouped together as 'string'.

Use the typeof operator to find out which variable type your variable is. Note, typeof will return 'object' for arrays, regular expressions and null in most current browsers. In future, browsers are instead expected to return 'null' for null.

Defining variables

See the section on 'Referencing' subsection 'Avoiding referencing conflicts' to see how to choose names for your variables.

Normal variables

It is good practice to pre-define all variables using the var keyword (this is known as declaring the variables). It is possible to define the variable, leaving its value undefined, or assigning a value immediately, or even to define multiple variables in a single command:

var variablename;
var variablename = value;
var vari1 = value, vari2 = anotherValue, vari3;

JavaScript is fairly lenient, and will create a global variable if you forget to use the 'var' keyword, but you assign a value to an undeclared variable (if you attempt to read the value of an undeclared variable, it will throw an error, as discussed below). However, this can lead to problems if you end up accidentally overwriting variables from another scope (this will be covered in the chapter on Functions). Once a variable is defined do not use 'var variablename' again unless you wish to completely overwrite the variable. It makes no sense to redeclare a variable with the var keyword within the same scope, but browsers will not complain if you do it.

These are some examples of how to define variables, in this case, a string, a number, and a regular expression:

var myFish = 'A fish swam in the river';
var myNumberOfGoats = 23;
var myPattern = /<[^>]*@[^<]*>/gi;

Note that variables can be defined at any point in your script, including inside a control structure that causes that statement never to be executed. However, no matter where you choose to define your variable, the JavaScript engine will create the variable at the start of the current scope. It will hold the value undefined until a statement is executed that gives it a value.

Objects

If you want to create variables that you want to be able to give child properties to, you must define the variable as an object. To define a variable as an object, use either the new Object() or {} syntax:

var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};

You can then assign child objects or properties to that object as you want:

variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();

Note that if you want to run a method on an object that you just created, for true JavaScript 1.2 compliance, you must surround the object declaration with brackets (early Netscape 4 will have problems otherwise). This example will not work in early Netscape 4, and other browsers made at the same time:

new Date().getTime()

This example will work in all JavaScript supporting browsers:

( new Date() ).getTime()

This applies to all object types like Array, Image, Option, Object, Date and ones you create yourself.

Arrays

Arrays are similar to the Object we have just defined, but with some small differences. I like to think of arrays as boxes. Inside the box, there are several compartments or cells. We can vary the number of compartments. To refer to the contents of a compartment, we write the name of the box, then we write square brackets, inside which we put the name or number of the compartment.
To create an array, use either the new Array() or [] syntax:

var nameOfArray = new Array();
var nameOfArray = new Array('content_of_first_cell','and_the_second',8,'blah','etc');
var nameOfArray = ['content_of_first_cell','and_the_second',8,'blah','etc'];

You can also use a single number as a parameter when creating the array object. If the number is a positive integer, an array will be created with that many cells, all of which will be empty: new Array(5). Note that if you set the language version to javascript1.2, some browsers (but not all) will create an array with a single cell containing the number 5. For this reason, it is best not to use a single numeric parameter when creating the array using the new Array(number) syntax.

To refer to the contents of its cells, use the syntax nameOfArray[name_or_number_of_entry] (if using names instead of numbers, the name should be in quotes). Numeric arrays start at 0, not 1, so the first cell is number 0.

In JavaScript, arrays and objects are almost equivalent, and accessing a named cell of an array is the same as accessing a property of an object. However, it is important to note that most of the special array functionality is based on you using numeric arrays - most array methods act only on numeric keys, and will ignore named properties. If you are using arrays with only named properties, then you are almost certainly using them for the wrong reason, and should probably be using objects instead. However, for the purpose of demonstration, if a cell of an array is called 'mycell', you could use either of these to access its contents:

nameOfArray['mycell']
nameOfArray.mycell

There are some important differences between arrays and objects. By default, arrays have far more methods attached to them, for stepping through a numeric array, or splitting it into pieces. In addition, if numbers are used for entries, you can find out how many entries (or variables) the array is holding, using nameOfArray.length

It is possible to create multi-dimensional arrays, by creating aditional arrays as the contents of the cell of another array:

var nameOfArray = new Array(new Array(1,2,3,4),'hello',['a','b','c']);

You can refer to the cells of that array using the square bracket notation twice (or multiple times, depending on how many dimensions your array has):

nameOfArray[name_or_number_of_entry][name_or_number_of_inner_entry]

Other types of objects

Browsers will have many built in types of objects. All JavaScript capable browsers will provide the following aditional object types:

Date
Creates a date object, which can perform calculations based on the date, for example:
var mydate = new Date();
window.alert( 'The year is' + mydate.getFullYear() );
Image
Creates an image that is not visible but is stored in cache. Setting the src attribute of the image causes the image to be loaded and stored in the browser's cache:
var myimage = new Image();
myimage.src = 'thing.gif';
Now each time I want to change an image on the page, I can say document['imagename'].src = myimage.src; and the image will change, without having to wait for the new image to load.
Option
Creates an option that can be added into a select input, for example:
var myoption = new Option('text','value');
selectInput.options[selectInput.options.length] = myoption;

See the section on 'Creating objects' for how to create your own objects that are not one of the pre-defined object types. DOM compliant browsers will provide far more object types - these will be covered in later chapters of this tutorial.

Deleting properties

On several occasions here I have created properties for objects. Even if these are set to undefined or null, they still exist, holding that new value, and will be found using the for-in control structure. You can delete them completely by using the 'delete' keyword:

delete myObject.itsProperty;

Of course, unless you have serious computer memory considerations, or security risks, it is usually not necessary to do this at all, since JavaScript engines clean up after themselves once the variable is no longer referenced.

Avoiding errors with variables

If at any time you refer to a variable that does not exist, you will cause an error. However, JavaScript allows you to refer to one level of undefined child properties of an object (specifically, it allows you to refer to non-existant properties of any variable that is not null or undefined, but it will not allow you to refer to their properties, since an undefined property cannot have properties of its own). This is a very important rule to learn, as it forms the basis of object and capability detection, and is fundamental to making cross browser scripts. The following series of examples will demonstrate what will throw errors:

var myObject = new Object(), nonObject = '', nonObject2;

This sets everything up for the following examples. So far, everything is fine, but in the code below, b is undefined. Not only that, but it has never been declared as existing. This will cause an error when the code attempts to read its value:

var a = b + 5;

In the code below, c has also not been defined or declared. It will not throw an error, however, because the code is assigning a value to it. This will cause the script engine to automatically declare it in the global scope:

c = 5;

In the next example, the parent object has been defined, but its property has not. Since this is only one level of undefined properties, this is allowed, and will not cause an error:

var b = myObject.myChild;

In the next example, the parent object has been defined, but its property has not. Trying to refer to a child of the non existent property means there are now two levels of undefined properties. This will cause an error:

b = myObject.myChild.itsChild;

The actual reason it causes an error is because the code attempts to access the property of an object that does not accept properties (implicitly 'undefined' in this case), and will cause an error if an attempt is made to access them. The same would happen if myObject.myChild was explicitly defined as null or undefined.

In the next example, the parent object has been defined, but it is a type of variable that cannot accept custom child properties, such as a number or string. Trying to create a child property will not throw an error, since it is only one level of undefined properties. However, it will not do anything, since the new property will be rejected:

nonObject.itsChild = 7;
window.alert(nonObject.itsChild);
//This will alert 'undefined'

Null and undefined are special, however, as they cannot have any properties at all, custom or native. Any attempt to access a property of a variable that holds the value null or undefined, will result in an error:

nullVariable = null;
nullVariable.itsChild = 7;
//This will throw an error

In the next example, the parent object has been declared, but it was not given a value. As a result, it holds the value undefined. Trying to refer to a child property means there are now two levels of undefined properties, and will throw an error:

nonObject2.itsChild = 7;

Referencing a variable or just its value

If you assign one variable to another, there are cases where this merely copies the value in one variable and 'pastes' it into the other, but there are also cases where instead of copying the variable, it just provides you with a new way to reference that variable. The following is an example of where this might occur:

var myNewVariable = myOldVariable;

If myOldVariable was already defined as a string, number, boolean, null or undefined, it would simply have copied myOldVariable and 'pasted' it into myNewVariable. If the new variable were changed (for example, using myNewVariable = 'some new value';), myOldVariable retains its old value.

If, on the other hand, myOldVariable was already defined as a function, array, object, regular expression or option (or any other type of object except null), myNewVariable would have been created as a pointer to myOldVariable. The children of myOldVariable would now also be the children of myNewVariable. If the new variable were changed (for example, using myNewVariable = 'some new value';), it would only alter the value of myNewVariable so that it no longer references the same contents as myOldVariable. However, changing the child properties of myNewVariable will change the properties of the object it references, and as a result, myOldVariable would also see the change:

var myOldVariable = new Object();
var myNewVariable = myOldVariable;
myNewVariable.newChild = 'Hello';
alert(myOldVariable.newChild);
//This will alert 'Hello'

More about numbers

JavaScript understands numbers in several formats, allowing you to specify numbers in hex, decimal, and octal. If a 0 precedes a number and there is no number higher than 7, the number is considered to be in octal (base 8) and if the number is preceded by 0x, then it is considered to be in hex (base 16) and can also contain characters A, B, C, D, E, F. Neither may contain decimal points.

With decimal numbers, 12e+4 may be used to replace 12x104 and 12e-4 may be used to replace 12x10-4 etc.

There are a few numbers that are held by the Math object and can be used as variables with the exception that you cannot assign values to them. These are known as constants. There are some constants available that give the document area of the window that is available for writing to. These require specific referencing to obtain and so have been included in the section on referencing items, objects and elements, subsection 'Window size'.

The available Math object constants are:

Math object constants
Math object property Value (approx) Mathematical equivalent
Math.E2.718e
Math.LN20.693ln(2)
Math.LN102.303ln(10)
Math.LOG2E1.442log2(e)
Math.LOG10E0.434log10(e)
Math.PI3.142Pi
Math.SQRT1_20.707(sqrt(2))-1 or sqrt(1/2)
Math.SQRT21.414sqrt(2)

Special string characters

There are a few string characters that can be escaped with a backslash and can be used to replace untypeable characters. These are:

\n
A newline character. Use this if you want to insert a line break into text.
\f
A form feed. Try not to use this ever. Use \n instead.
\r
A carriage return. Try not to use this ever. Use \n instead.
\t
A tab character.
\\
A \ character
\/
A / character (most web developers [myself included on occasion] forget this one - generally, browsers will have no trouble with you forgetting the backslash but it is important for representing closing tags and in theory you should always use the backslash escape when writing a forward slash - see the section on Writing with script for details of where it is needed)

If you need to recognise a Windows linebreak, you need to look for \r\n. If you are trying to add a linebreak (for example, when modifying the value of a textarea input), you should insert a \n character. This will work cross browser. Note that browsers on Windows may convert this \n character into a \r\n automatically, depending on where you use it.

Old Mac Operating Systems (OS 9 and below) used \r for linebreaks, but as far as my tests showed, they are converted to \n by JavaScript. However, just be aware that you may encounter some of these, especially in text inputs (Mac OS 9 is still in use among some Mac users). Unix based Operating Systems (including Mac OS X) use \n for linebreaks.

If you are writing a string that contains double quotes, the easiest way to deal with it is to surround it with single quotes. You should also use double quotes if your string contains single quotes:

var mystring = 'And he said "help" twice';
var mystring = "Help Andy's cat";

You may notice a problem. What if you have both single and double quotes in your string? The solution is to use the escape character '\' to excape the quotes (in fact, you can always escape quotes, even if the string is delimited by the other type of quotes). For example, both of the following are valid:

var mystring = 'And he said "help Andy\'s cat" twice';
var mystring = "And he said \"help Andy's cat\" twice";

If your string becomes too long to fit on one line (this really doesn't matter - you can make the text as long as you want), and you want to split it onto several lines, simply end the string, follow it with the concatenation operator + and start a new string on the next line:

var mystring = 'first line of the string ' +
    'still on the first line of the string - it\'s like we never broke the line';

Note, in theory, you can use \ to break the string:

var mystring = 'like \
  this';

But this has significant problems; the \ will not always cope with trailing whitespace, may or may not correctly treat the leading whitespace before the new line, and does not work correctly in all JavaScript implementations:

I mention this only for completeness. Do not use it. It is easier and better to use the concatenation operator as shown above.

Regular expressions

Certain methods, like the stringObject.replace() and stringObject.match() methods, can recognise patterns in text. To do this, they use regular expressions. These are well documented elsewhere so I will not describe the syntax here. Basically, what you can do is use special characters to recognise text patterns (like \w for characters a-z, A-Z, 0-9 and _). To define a collection of characters as a regular expression, you use the / character (sometimes with a g or i after it). For example, the regular expression /\/\*[\w\W]*\*\// matches block comments.

Some rare browsers do not support regular expressions. In theory, you should be able to detect regular expression support using this:

if( window.RegExp ) { var myRegularExpression = new RegExp("pattern"); }

This should not produce errors in Pocket Internet Explorer and Internet Explorer for Windows CE (as they do not understand the /pattern/options syntax or support the RegExp object). However, as Opera 6- and iCab 2- support the RegExp object, but fail to use it correctly, your scripts will still fail, though hopefully without errors. Thankfully, current releases of Opera and iCab do support regular expressions correctly.

Last modified: 19 March 2011

  1. Previous
  2. Next
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.