Variables and assignment

Variables are used to hold items of data which are used and manipulated by JavaScript. A new variable is created with the var statement.

The name of the variable is always supplied by the programmer and cannot contain spaces.

Variables can hold text data, numerical data, true / false (boolean) data or object data which could refer to a specific row in a database table or a chunk of HTML code.

Variables are assigned values with the assignment operator =. In every case the right side of the assignment operator is the value being assigned and the left side is the name of the variable it is being assigned to.

A few simple examples

<script type="text/javascript">

// create a new variable called myName and assign the value "Andrew"
// Text values (known as Strings) are always surrounded by "s
var myName = "Andrew"	

// create a numerical variable called myScore and assign the
// number 10 to it.
var myScore = 10;

// create a boolean variable called lostPatience and set it to 
// false.  Boolean data can only ever be true or false, no other 
// value is permitted.
var lostPatience = false;

</script>

Exercise!

Now open the variables and assignment exercise and work through it.

You may also use the JavaScript scratch pad to try out code quickly.