Next page | Contents page |

Data types, variables, comments

There are only a few rather general predefined data types in Javascript:

We will of course be giving details of each of those in subsequent pages.

Variables

Locations in memory for storing data values. They are given names (identifiers, that the programmer makes up) so that we can keep referring to them. The value assigned to a variable may not be intended to vary (a constant in fact) but that doesn't alter the fact that we put it in a place called a variable.

It is good practice (but not required in JavaScript) to declare variables with keyword var before they are first used, to give them names, allocate memory for them and (optionally) give them initial values:


 var age, nCustomers;    // value: undefined (keyword)
 var paid = false;
 var latitude = 55.0, longitude = -0.5;
 var CM_PER_INCH = 2.54; // A constant

Notice that in the first of these examples age and nCustomers are declared but no values are assigned to them. After this, until something is assigned to them, they have the value undefined (a keyword). You can test (see later) whether a variable has that special value.

So after those 4 statements the system would have allocated some bytes somewhere in memory, labelled so they can be recalled again and containing values like this:

age
undefined
nCustomers
undefined
paid
false
latitude
55.0
longitude
-0.5
CM_PER_INCH
2.54
 

There is no way in JavaScript of telling the system that a constant may only be assigned a value once. (There is no const or final keyword, such as C or Java programmers would use.)

Equally there is no way to say that a particular named variable can only hold data of a particular type. A variable can be reused for anything really, but we would not recommend that. In other words, JavaScript does not use strong typing as, say, Java does. That makes for flexibility but with increased risk of making mistakes. Try to be aware of the types of data you are using in everything you write. You can of course make the data type a part of each variable name if you feel that would help you (not many do that though; it was a benefit of the Hungarian notation that C/C++ programmers in particular used to use, and we have advised against that! - you decide, but be consistent).

Comments

There are two kinds (the same as in C++ or Java):

It is not difficult for web users to see the JavaScript code and the comments embedded in it. So do not put anything in the comments that should not be seen publicly. It is possible to write programs to strip out comments as a step in publishing to the web but that is beyond the scope of this course.

We gave some other guidelines on the use of comments in Part 1.

Next page | Contents page |