Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www.austin.cc.tx.us/baldwin/

JavaScript Programming, Data Types, Literals, and Variables

Java/Web Programming, Lecture Notes # 2105, Revised 05/23/98.

Preface

The material was prepared as part of a new tutorial that I plan to publish on Web programming in general.  It is not part of the Java academic curriculum at ACC.

The purpose of this series of lessons is to teach you how to program in JavaScript.  The goal is to provide a programming tutorial that will be accessible to persons with no programming experience and will be equally useful to persons who already have programming experience using JavaScript or some other language.

 

Introduction

In the English language, individual characters of the alphabet are combined to make words.  Words are combined to make sentences.  Sentences are combined to make paragraphs.  Paragraphs are combined to make...  Hopefully you get the picture by this point.  The products of a language are constructed from fundamental building blocks.

In JavaScript and many other programming languages as well, literal values, variables, function calls, and operators are combined to create expressions.  Expressions are combined to create statements.  Statements are combined to create programs.

Therefore, we need to begin with the fundamental building blocks and work our way up from there.  In particular, we need to learn about literal values, variables, function calls, and operators.

You learned something about function calls in an earlier lesson.  We will learn about operators in a subsequent lesson.

This lesson will concentrate on literal values and variables.  Before we can do that, however, we will need to learn about the types of data that JavaScript supports.
 

What Do We Mean By Type of Data?

Some programming languages, such as Java for example, are very particular about data types.  JavaScript, is a loosely typed language and the programmer doesn't need to have too much concern about data types.  However, it is necessary for the programmer to know what types of data are supported by JavaScript in order to use those types appropriately.

JavaScript recognizes and supports the following types of data:

JavaScript makes no distinction between numbers with decimal parts and numbers without decimal parts (known as real numbers and integers in other languages).

JavaScript will automatically convert data from one type to another on an "as needed" basis during script execution.
 

What Is A Literal Value?

Literals are fixed values that you provide in your script.  For example in the expression
 
net = gross - 120
 
the 120 is a literal value and is commonly referred to as a literal.  You use literals to represent fixed values in JavaScript. There are several different kinds of literals and they are discussed in the following sections.
 

Integer Literals

When we speak of integers, we are normally referring to numeric values that don't have a decimal or fractional part.  For example, the number of whole apples in a barrel is an integer because whole apples don't have fractional parts.

However, the distance in miles between your house and your friend's house is probably not an integer.  It is what math teachers refer to as a real number.  It does have a fractional part.  For example, it may be 3.6 miles from your house to your friend's house. (If you believe that it is exactly 3 miles to your friend's house, you probably didn't measure it accurately enough.)

To understand the following material, you need to know a little about raising numbers to powers.  If you don't know about that, I strongly urge you to find a high school algebra book and brush up on it.

We are accustomed to working with numbers designed according to the base ten (possibly because we have ten fingers).  We refer to this as decimal notation.  A number, such as 306,  in decimal notation, can be thought of in the following way:
 
346 = 3x100 + 0x10 + 6x1
 
In this notation, 3, 0, and 6 are referred to as coefficients, while 100, 10, and 1 are referred to as powers of ten.

Stated differently, 100 is ten raised to the second power, 10 is ten raised to the first power, and 1 is ten raised to the zero power (your high school algebra teacher should have told you that any value raised to the zero power is 1).

Note that the coefficients can take on any integer value between 0 and 9, or ten possible values in all.

You are not confined to number systems designed to operate on the base ten.  You can learn to do arithmetic using a number system based on any value (but it may be a challenge in some cases).

While decimal notation is usually most convenient for humans, it isn't the most convenient for the inner working of computers.  Modern digital computers use the base two instead of the base ten.  This is often referred to as binary notation or the binary number system.

While it may not be immediately obvious, the number of possible coefficient values for any given base is the value of the base.  We saw that the number of coefficients for the base ten is ten.  Thus, the number of possible coefficients for the base two is two.  We commonly use 0 and 1 as the symbols representing those coefficients.

The binary system is tedious and difficult for humans to work with.  Relatively small values result in a large number of digits.

Over time, programmers have developed a couple of crutches to make it easier to work with internal computer data.  Without attempting to explain why, let me simply say that in the early days of computers, a popular crutch was a number system based on eight, and commonly known as the octal number system.  This system is rarely used today.

The second crutch which is in widespread use today is a number system based on sixteen.  This is commonly referred to as the hexadecimal number system

A number in the hexadecimal system represents a series of coefficients, each having 16 possible values, multiplied by a series of powers of 16.  The reason this is popular is because it is easy to mentally convert between base 16 to base 2. Thus programmers can easily convert between something that is relatively easy for them to handle and something that is easy for the computer to handle.

Since the coefficients can take on 16 different values, it was necessary to invent some new symbols to represent the coefficients.  The sixteen symbols in common use are:
 
 
0 1 2 3 4 5 6 7 8 9 A B C D E F
or
0 1 2 3 4 5 6 7 8 9 a b c d e f
 
Why am I telling you all of this?  Because JavaScript can represent literal integer values in any of three different ways:  decimal, octal, or hexadecimal. When you specify a literal integer value, you use a specific syntax to also specify which number system it represents.

A literal decimal integer literal consists of a sequence of digits without a leading 0 (zero).

A leading 0 (zero) on a literal integer indicates that it is in octal.

A leading 0x (or 0X) indicates hexadecimal.

We already know that the decimal system allows the digits (0-9).

As mentioned above, hexadecimal integers can include the digits (0-9) and the letters a-f and/or A-F.

By now it should be obvious that Octal integers can only include the digits (0-7).

We will see examples of integer literals in a sample script later in this lesson.
 
 

Floating-Point Literals

The previous section discussed integers and mentioned that there are also some numeric values that are not integers (such as a measure of the miles to your friend's house).

Typically these numeric values will include a decimal point which can occur anywhere in the number.  They consist of a whole number part and a fractional part.  These are often referred to as floating-point values.

Two different notations are often used in computer input and output to represent values of this type:

  1. floating point notation
  2. exponential notation.
Examples of both follow:
 
6258942.123 = 6.258942123E06
 
The example on the left shows the value in floating point notation.  Interpretation of this value should be obvious to you.

The example on the right shows the same value expressed in exponential notation (sometimes called scientific notation).

The interpretation here is that the actual value is the value shown to the left of the "E" multiplied by ten raised to the power shown to the right of the "E".

In this particular case, the value to the left would be multiplied by ten raised to the sixth power (one million) to obtain the actual value.

In JavaScript, a floating-point literal can have the following parts, some of which are optional:

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). The entire number can also be signed.

A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

We will see examples of floating point literals in a sample script later in this lesson.
 

Boolean Literals

A literal boolean value is very simple.  It can have only one of two values:  true and false. Note that when you specify a boolean literal, you do not surround the word with quotation marks.  That would cause it to be a string literal which is the topic of the next section.
 
 

String Literals

A literal string consists of zero or more characters enclosed in (delimited by) double (") or single (') quotation marks.

A string must be delimited by quotation marks of the same type; that is, either both must be single quotation marks or both must be double quotation marks. Examples of valid literal strings follow:
 
"Dick Baldwin"
'Dick Baldwin'
"First line \n Second Line"
 
It is also possible to include special characters in a string as shown in the third line above.  These special characters are characters which cannot ordinarily be entered into a string directly via the keyboard (such as a newline character or the Enter key).  For example, pressing the Enter key on the keyboard doesn't cause the newline character to become part of the string, it simply causes the cursor in your editing program to move to the left of the next line down the screen.

The following table lists the special characters that you can use in JavaScript strings. In all cases, you prefix the character with a backslash character.
 
 
Character  Meaning 
\b
backspace
\f
form feed
\n
new line
\r
carriage return
\t
tab
\\
backslash character
\"
double quotation
 
To include a double quotation mark in a literal string, you must precede it with a backslash.  We will see examples if this syntax in subsequent lessons.  To include a backslash in a literal string, you must also precede it with a backslash.



Variables

Think of variables as symbolic names for values in your application. Perhaps more appropriately, think of them as names or references to locations in memory where you will store specific values.

Variable names must conform to the naming rules for identifiers.

A JavaScript identifier must start with a letter or underscore ("_").  Following this, you can use either letters or the symbols for the digits (0-9).

JavaScript is case sensitive.  Therefore letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

When working with variables in JavaScript and other languages as well, you must always be concerned about an issue known as scope.  Scope determines which statements in a program have access to a variable, and in some languages determine the lifetime of the variable.

In most languages, including JavaScript, you must declare a variable before you can use it.  However, JavaScript is very loose in this regard.  There are two ways to declare a variable in JavaScript:

By simply assigning it a value; for example, x = 10
Using the keyword var; for example, var x = 10

JavaScript recognizes two kinds of variables:

Local variables are variables that are declared inside a function.  Global variables are variables that are declared outside a function.

Local variables may only be accessed by other code within the same function.  Global variables may be accessed by any code within the document.  Special considerations apply when working with HTML frames.  We will discuss these considerations when we study frames.

Using var to declare a global variable is optional. However, you must use var to declare a variable inside a function.

Sample Script

The following sample script illustrates a number of the things that we have been discussing in the previous sections of this lesson.
 
<!-- File Js00000070.htm
Copyright 1998, R.G.Baldwin 
This JavaScript script is designed to illustrate the
use of literals and variables of several different types.
---------------------------------------------------------->
<HTML>
  <HEAD> 
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script 

      //Define the function named getArea()
      function getArea(theRadius) {
        var theArea;//declare a local variable
        //calculate the area
        theArea = 3.14159 * theRadius * theRadius;
        return theArea;
      }//end function getArea()

      // End hiding  -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <SCRIPT>
      var area;//declare a global variable
      area = getArea(3.1);//call the function with a float
      document.write("Area is: " + area + "<BR>");
      area = getArea(5);//call the function with integer
      document.write("Area is: " + area);
    </SCRIPT>
    <P> Done.
  </BODY>
</HTML>
 
For example, it isn't difficult to pick out a local variable, a global variable, and literals of type float, string, and integer (but remember that JavaScript really doesn't make a distinction between float and integer numeric values).

-end-