/

HTML / CSS / JavaScript Tutorial

JavaScript Tutorial

2. Variables

[this page | pdf | back links]

A variable in JavaScript is defined by a command such as:

 

var x;

 

If you want to set a variable to a value when it is first defined then you generally use the assignment operator within this definition, e.g.:

 

var x = 10;

 

JavaScript recognises the following types of ‘primitive’ variables:

 

-        String variables

-        Number variables

-        Date variables

-        Boolean variables

 

Variables can also be objects and arrays (and for some string manipulation purposes, regular expressions). In JavaScript, an array is a special type of object that is indexed along the lines of a[0], a[1]…. Arrays can consist of other objects, including other arrays.

 

Several variables can be defined in the same statement, with each one separated by a comma, e.g.:

 

var x = 10, y = 15, z = 20;

 

Variables that have not yet been defined a value have their value as undefined.

 

If you redefine a variable, it retains its previous value. For example, after the statements

 

var x = 10;

var x;

 

the variable x still has the value 10.

 

Variables are manipulated using operators and functions. For example, numbers can be added together using the addition operator or functions can be applied to them, e.g.:

 

var x = 0.1 + 0.2;

function sinsquared(x) {

  var a;

  a = Math.pow(Math.sin(x),2);

  return a;

}

var y = sinsquared(0.3);

 

JavaScript variable names (i.e. identifiers) follow certain rules:

 

-        They can contain only letters, digits, underscores and dollar signs

-        They must typically begin with a letter (in some cases they can also begin with a $ or an _ character)

-        The names are case sensitive (i.e. a and A are different names)

-        They cannot be reserved words, such as those used in JavaScript statement construction)

 

An important concept in programming is the scope of a variable (or more precisely of its name). This is the part of the code within which the relevant variable is accessible via its name. If code is segmented into blocks then it is often desirable to use a similar variable name in different blocks but for the names to then be associated with different variables depending on the block in question. The scope of a JavaScript can be local or global. Variables defined inside functions are local to that function, whilst those defined outside functions are global in scope. Local variables are deleted when the function completes, while global variables remain available until the user closes the browser window or tab within which the page has been loaded. This means that they are available to new pages loaded into the same browser window. Function arguments work in the same manner as local variables inside a function.

 

String variables

 

Strings consist of a series of consecutive characters, e.g.

 

var x = "Cat";

 

A string technically consists of a series (an ‘array’, except that a JavaScript array is a specific type of variable) of characters, which is zero-indexed. So, if we assigned x the value of "Cat" then x[0] would be "C", x[1] would be "a", etc.

 

Further details on the methods and properties supported by string variables are set out in JavaScript Tutorial: Strings.

 

Regular expressions

 

Some string methods and properties involve ‘regular expressions’. These take the form:

 

/pattern/modifiers

 

e.g.:

 

var x = /nematrian/i;

 

Further details on the methods and properties supported by regular expressions variables are set out in JavaScript Tutorial: Regular Expressions.

 

Numbers (and mathematical manipulations)

 

JavaScript has only one type of number (in contrast to, e.g. Visual Basic, which differentiates between e.g. integers, floating point numbers and double precision numbers). Numbers can be written with or without decimal points and/or with or without (scientific) exponents), e.g.

 

var x = 4.1;    // With a decimal point

var y = 4;      // Without a decimal point

var p = 135e6   // Means 135000000

var q = 13.5e-3 // Means 0.0135

 

Further details on the methods and properties supported by numbers and by the Math object (which can be used to carry out mathematical manipulations) are set out in JavaScript Tutorial: Number variables and mathematical functions.

 

Dates

 

Date variables are objects and contain dates and times. They can be instantiated in 4 ways:

 

var d1 = new Date();          // An as yet undefined date

var d2 = new Date(milliseconds);  // See below

var d3 = new Date(dateString);   // See below

var d4 = new Date(year, month, day, hours, minutes, seconds, milliseconds);

 

Here milliseconds refers to the number of milliseconds since 1 January 1970 00:00:00. A dateString is a piece of text that the browser can recognise as representing a date.

 

Further details on the methods and properties supported by numbers and by the Math object (which can be used to carry out mathematical manipulations) are set out in JavaScript Tutorial: Dates.

 

Booleans

 

Boolean variables take one of two values, true or false. They are instantiated by a statement such as:

 

var b = true;

 

You can use the Boolean() function to identify whether an expression is true or false, although it is simpler just to use operators that return Boolean outputs, e.g. Boolean(2 > 1), (2 > 1) or even 2 > 1 all return true.

 

Further details on the methods and properties supported by Boolean variables are shown in JavaScript Tutorial: Booleans.

 

Arrays

 

Arrays contain multiple (indexed) values in a single variable. Array indices are zero-based, i.e. the first element of the array has as its index 0, the second 1 etc. They are instantiated by statements such as:

 

var a = ["France", "Germany"];

var b = [1, 2, 5, 4];

 

It is worth noting that elements of arrays can themselves be arrays since technically an array is a specific type of object.

 

Further details on the methods and properties supported by arrays (and some of the subtleties that arise if you want to copy them) are set out in JavaScript Tutorial: Arrays.

 

Objects

 

JavaScript objects are containers that contain properties and methods. For example, a statement such as:

 

var person = {title:"Mr", surname:"Smith", age:30}

 

creates an object that has three properties, i.e. name-value, pairs that in this instance characterise (some of the features of) a person.

 

Object properties can be accessed in two ways, either here e.g. person.title or person["title"] (both of which in this instance would return a value of "Mr"). An array is a specific type of object with the property names indexed from 0 up to the length of the array less 1 (and hence elements of arrays can themselves be arrays or other sorts of objects).

 

Object methods are functions that can be applied to objects. They are technically also property-like in nature, i.e. again come in name-value pairs, but with the ‘name’ being a function name (with parameter definitions if necessary) and the ‘value’ being the JavaScript function script associated with that function, see JavaScript Tutorial: Objects.

 

A special type of object is the Error object, which is used for error handling.

 


NAVIGATION LINKS
Contents | Prev | Next | JavaScript


Desktop view | Switch to Mobile