Skip to content
Science, Maths & Technology
Author:

Variables and Data Types

Updated Tuesday 23rd June 2015

Learn about variables and how a program interacts with some different stored data types using JavaScript.

Variables

Keyboard Copyrighted image Icon Copyright: Dreamstime

Writing programs which simply display words that you have already written as part of the program (source) code isn't terribly interesting. We want you to be able to write programs which will take data, manipulate it in some way and then display the results. Before you do that, you need to have some idea of how a JavaScript program can access data stored in the computer's memory. Locations in the computer's memory have unique addresses but when using a high-level programming language such as JavaScript, we don't need to know anything about exact memory locations; we can simply declare to JavaScript that we require some memory, and give it a name, sometimes referred to as an identifier. The JavaScript interpreter and the operating system will then identify a suitable memory location and manage it for us.

A variable can be thought of as a named location in the computer's memory where a value is stored. You can think of the name (or identifier) as a sort of label for the memory location. For example, a variable called sum might have the number value 3 stored in it.  We say that the variable named sum has the value 3, or is assigned the value 3.

As its name implies, the value in a variable can change (vary) as the program executes (i.e. carries out the instructions in the program). When a program accesses a variable, such as sum, it will use whatever is its current value. You will see later that you can choose any name for a variable, provided it is consistent with certain rules. Remember that JavaScript is case-sensitive and that all reserved words must be in lower-case characters. Where we include program code here, we will use bold font for reserved words.

The following three lines are the JavaScript code from variables_activity_1.html (which you may look at using your text editor if you wish).

var myVar;
myVar = 3;
document.write(myVar);

In the first line, var is a reserved word (also known as a keyword). The line
var myVar;
is the declaration of a variable with name myVar, i.e. the program is told to use myVar as the name for a location in the computer's memory where some data will be stored. With this line alone, myVar doesn't yet have a value.

The second line,
myVar = 3;
assigns a value of 3 to myVar, i.e. puts the value 3 in the memory location labelled myVar.
The symbol = in JavaScript is called the assignment operator: any value on the right of the = symbol (3 in this case) is assigned to the variable named on the left, myVar.

The third line,
document.write(myVar);
writes the current value of myVar into the browser's current page. Notice that myVar is not enclosed in quotes, as we want to display the value of the variable called myVar, in this case 3, not the text 'myVar'.

Question: Suppose we have a variable called total, which is assigned the value 5.

var total;
total = 5;

How will JavaScript interpret each of the following lines of code?

(a) document.write('total');
(b) document.write(total);

Answer

(a) The word total will be displayed in the browser's current page.
(b) The number 5 (the value stored at the memory location labelled total) will be displayed in the browser's current page.


The semicolon and sequential execution

Sequential execution means carrying out one instruction, and the next, and then the next, and so on until all the instructions have been executed. All the programs we'll be examining execute in this way.

Here again are the three lines of JavaScript code from variables_activity_1.html:

var myVar;
myVar = 3;
document.write(myVar);

You may have noticed that there are semicolons at the end of each line. The semicolon is used as a separator between instructions, so that JavaScript clearly 'knows' where one instruction ends and another begins. Of course, JavaScript is not capable of 'knowing' in the human sense, but you will find that ascribing human characteristics to things (known as anthropomorphism) is common in discussions of computer hardware and software. Where each instruction is on a separate line the semicolons are not mandatory, but we think they make the code clearer and will be using them throughout.


Activity 1

Now you are going to make some changes to the JavaScript code of variables_activity_1.

1. Open the file in your browser to remind yourself what it does.

2. Now open the file in your text editor. Change one line of the JavaScript source code so that the output displayed is 145.

Save your changes and open the file in your browser again to check that your change has the desired effect.

Help

1. You will see that the output is the current value of the variable, myVar, which is 3.
2.Changing myVar = 3 to myVar = 145 will achieve the required change.
 

Now replace the second line of JavaScript code in your copy of variables_activity_1 with 3 = myVar; and try to run the program. What happens?

The answer should be that nothing happens. When assigning a value to a variable, the name of the variable must be on the left-hand side of the = symbol, and the value on the right. The items on either side of the = symbol in JavaScript are not of the same kind: on the left there is a variable name (which is just a name for some memory location); on the right there is some kind of value – either an explicit value or an expression that will evaluate to a value. For example, if myVar and yourVar had both been declared as variables, the following would all be valid examples of assignment statements.

myVar = 6;
yourVar = myVar + 3;
myVar = yourVar;

Question: Suppose that the variables myVar and yourVar have already been declared. What would each of their values be after each of the following lines of JavaScript have been executed in sequence?

(a) myVar = 3;
(b) yourVar = myVar + 2;
(c) myVar = yourVar;

Answer

(a) The value of myVar is 3; we don't yet know anything about the value of yourVar.
(b) The value of myVar is still 3; the value of yourVar is the value of myVar plus 2, i.e. 5.
(c) The value of myVar is the value of yourVar, i.e. 5; the value of yourVar is still 5. (But note that there are still two seperate memory locations; they just happen to hold the same value.)

Variables are often compared to named boxes or pigeon-holes. Although this helps us to visualise what's happening in the computer, the comparison is not entirely appropriate, as we can normally add a number of items to a pigeon-hole whereas a variable can only hold one value at a time. If a new value is assigned to the variable, then this value overwrites the previous value, which is lost.

Question: 

(a) What are the two stages in executing the following instruction (where yourVar is a variable)?
yourVar = yourVar + 3;
(b) If the value of yourVar before execution of the statement is 10, what will its value be after execution of the statement?

Answer

(a) First of all, the expression on the right-hand side will be evaluated, i.e. 3 will be added to the current value of yourVar. Then this new value will be assigned to yourVar.
(b) Its value will be 13 (the result of 10 + 3).

What is the value of the variable myVar after both the following lines have been executed?
myVar = 21;
myVar = myVar - 5;

Answer

The value of myVar is the value assigned to myVar in the first line (21) minus 5, i.e. 16.


Naming variables

In the examples we've used so far we have used sum, myVar,and yourVar as variable names. The name sum might indicate to a reader that the value of the variable holds the sum (total) of some other values; the names myVar and yourVar give no clue as to the role played by these variables (they were actually used to make teaching points, rather than to carry out a specific task). We recommend that you name variables in such a way as to indicate the role that the variable has in carrying out your particular programming task. We mentioned earlier in this subsection that names for variables are sometimes referred to as identifiers. The distinction between the two is rather subtle. An identifier in a program is a name that must follow particular rules (which vary between programming languages). All names allocated by the programmer, such as those for variables, methods and so on, must be valid identifiers. You will find that name and identifier are often used interchangeably in books about programming. In JavaScript identifiers must conform to the following format.

  • The first character must be one of the following:
    • an upper-or lower-case letter (that is, A...Z, a...z);
    • an underscore character (_);
    • a dollar sign ($).
  • Subsequent characters may be any of the above or a digit (0, 1, 2, ..., 9).
  • You may not use a reserved word which is already part of JavaScript's vocabulary. (You have already seen var as a reserved word signalling a variable declaration; you will later see other reserved words, such as while, if, for.)

The above rules governing identifiers are mandatory. However, we encourage you to respect the following style guidelines when choosing identifiers for your variables. Sticking to these guidelines will make your programs easier to read and (if necessary) debug.

  • Although there is no lower or upper limit on the number of characters that can be used in an identifier, we would urge you to avoid very short identifiers, such as a, b, x, ch, because they are not very informative.
  • As far as possible, avoid the use of $ and _ in identifiers. Identifiers composed entirely of letters are usually the most meaningful to human readers, though it might sometimes be appropriate to use digits in identifiers for a number of similar values, e.g. sum1, sum2, sum3.
  • Choose meaningful names, i.e. names which give some indication of the role played by the variable.
  • Start your identifiers with lower-case letters. Where an identifier is composed of two or more English words, then we suggest the use of a single upper-case letter to mark the start of each word after the first. We have used this style of identifier (known as camel-backed identifiers) for myVar and yourVar. Here are a few more examples: totalCost, dateToday, myFamilyName.

 Question: Which of the following are valid identifiers in JavaScript?

123
$sum
PriceAsked

Answer

123 is invalid – an identifier must start with a letter, _ or $.

$sum and PriceAsked are both valid, though they don't conform to our style guidelines!

Given that programming languages were designed primarily as a way for people to communicate with computers, why should programs be easy for people to read, as well as to write?

One reason is for ease of debugging: if your program doesn't run at all, or if it doesn't run as you expect, you need to be able to find your mistake. This involves reading the program code and understanding what it does. Another reason is that you may wish to modify an existing program, rather than write one from scratch, in order to solve a particular problem or to carry out a particular task. Again, it is important that you understand what the existing program does. You may have thought of other reasons.


Activity 2

Open up the following file in your preferred text editor - variables_activity_2.html. You'll notice it's very similar to the version we used previously.

Delete the line
myVar = 3;
so that the JavaScript code now reads:
var myVar;
document.write(myVar);

Save your changes and open the program in your browser.

You will get the word undefined displayed in your browser's current page. This is because the variable myVar has not had any value assigned to it.

The process of assigning an initial value to a variable is called initialisation – until you initialise a variable it will not have a value.

If you want to try something a little more complicated, try editing this code to do the following:

  1. Name your variable myNumber, or another new similar, valid variable name
  2. Initialise your variable with the number 7
  3. Add 3 to your variable's value
  4. Display the value of your variable on the screen.

If you have trouble with this, click below to view the correct code. Try to think of where you might have gone wrong first though. Remember your code is executed sequentially!

Answer

var myNumber;
myNumber = 7;
myNumber = myNumber + 3;
document.write(myNumber);


Some useful data types

Some of the data values that we have seen so far are recognisably of the same kind, or type. For example, the values 3, 7, and 21 are all of the number type, as indeed are 3.24, –6 and –2.5.
Similarly, 'hello', 'welcome' and 'have a good day!' are all recognisably sequences (or strings) of characters. In JavaScript, as in many other programming languages, character sequences are represented by the string type. As you have already seen, strings in JavaScript code must be enclosed in quotation marks to distinguish them from variables and reserved words; the quotes are not actually part of the string. Strings can include spaces, punctuation marks, indeed any character you would find on a typewriter keyboard, as well as letters. Many programming languages also treat whole numbers differently from real numbers (numbers with decimal parts), but JavaScript does not.

It isn't always obvious to which type a value belongs. Take 6123456, for example: is this a number, or is it a string, i.e. a sequence of (numeric) characters such as those found on a keyboard? The answer depends on the role of 6123456 in the context of the program. It might be the number of people watching the first episode of a series on television. In this case, it is clearly a number. You can imagine using it in calculations, such as adding the number of people who watched subsequent episodes, or finding the difference between this and the number of people who watched a film on another channel at the same time. On the other hand, 6123456 might be a telephone number, in which case it seems unlikely that you would want to use it in calculations, and so you could think of it as the character string '6123456'. To indicate to JavaScript that a sequence of numbers in a program is to be treated as a string, we must include the quotes.

Hopefully now you should have a good understanding of what a variable is and an idea of some of the ways that they can be used.When you're ready to continue, pick your next lesson from the menu below. We recommend 'Operators' next.

 

Author

Ratings

Share

Related content (tags)

Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?