Web Developer

JavaScript Basics

Based on our last example, the validation of our contact form, we're beginning to see the power of embedding scripting code in our web pages.  What we've seen so far though is just the tip of the iceberg.  By embedding scripting code in our web pages, we can make our pages do things undreamed of just a few short years ago.  HTML and CSS provide a good deal of flexibility to developers but the end result is merely a static page.  Adding scripting code allows us to make changes to our pages after they are loaded.

There are actually two major scripting languages: JavaScript and VBScript.  Why, then, are we not covering VBScript as well?  The simple answer is that VBScript is a Microsoft product and is only supported by Internet Explorer.  For obvious reasons, Netscape's browser doesn't support VBScript.  JavaScript, on the other hand, although invented by Netscape, has been passed on to a specification body (ECMA - the European Computers Manufacturing Association).  It is no longer controlled by a single company.  Also, since JavaScript has been around longer than VBScript, both major browsers have supported it since version 3.  The result is that if you want to write scripts that both major browsers will support, JavaScript is your only choice.

Before we begin, let's discuss what JavaScript is not.  JavaScript is not a subset of the Java programming language (as VBScript is a subset of Microsoft's Visual Basic).  Java is a full strength, compiled programming language.  A compiled language is translated from English-like commands to a machine language only once - at compile time.  JavaScript, on the other hand, is an interpreted language.  An interpreted language must be translated into machine code each time it is run.  Java is an object oriented language - everything that happens in a Java program is done by an object.  JavaScript is an object based language - it does not contain some of the facilities that a truly object oriented language must have to be object oriented (polymorphism and inheritance come to mind).  It will help us, though, to think in terms of objects when we write JavaScript.  More on that a little later.

So what can we do with JavaScript?  The answer is a lot of things!  We've already seen that we can validate our forms.  JavaScript allows us to manipulate the browser itself, play sounds, create animations, perform calculations, and even write web pages on the fly.  It provides a fairly complete set of functions and commands to manipulate the Document Object Model (DOM) and it can make your web pages seem to come alive when compared to static HTML pages.

If you've done any programming at all, especially in C or Java, JavaScript will seem almost familiar to you.  Many of the familiar programming constructs are present such as loops, conditionals, assignment, arrays, functions, methods, and variables.  There are some simple rules that apply to JavaScript:

The JavaScript Building Blocks

Using Identifiers

An identifier is a unique name given by you to a variable, function, method, or object in your script.  As with many other programming languages, JavaScript has some rules regarding the names you can choose as identifiers.  All JavaScript identifiers must start with a letter or the underscore character.  They may contain both upper and lowercase letters (but, remember, JavaScript is case sensitive!).  Identifiers may also contain the digits 0-9 but the digit cannot be the first character in the identifier.  Identifiers cannot be JavaScript reserved words.  The short of it is that identifiers are simply names you assign to things.

JavaScript contains both variables and literals (constants).  As their names indicate, variables hold data that may be changed when the script is run.  Literals hold data that can't change when the script is run.  Usually, you will assign a literal to a variable as in:

contact.firstName = "Tom";

In the above example, we assume that there is an object called contact.  The contact object has a property called fristName to which we've assigned the String "Tom."  Both contact and firstName are identifiers and variables.  "Tom" is a literal.  You can change the literal assigned to firstName but you cannot change the literal "Tomn" - it would just be another literal!

Literals and variables can contain data of several types summarized below:




Integers are literals consisting of numbers only and they are restricted to whole numbers (as opposed to Floats below).  You can specify to use octal (base 8) or hexadecimal (base 16) numbers by prefacing the number with either 0 or 0x.

Floating Point Numbers

Floats are numbers with decimals that can contain exponents.  Examples include 3.14159 or 6.02e23.


Strings represent words, characters, or data and are set off by using either single or double quotes.  In order to use special characters you must use escape symbols like \n for newline or \t for tab.  To include a quote inside a String, use \" for a double quote or \' for a single quote.


Boolean literals hold a value of true or false.

Here are the cool parts:  With JavaScript you specify the type of variable simply by assigning a literal to a variable.  Once you assign a value, you have implicitly identified a data type.  Additionally, you can change the type of data held within a variable simply by re-assigning a new data type.

Functions, Objects, and Properties

An object is nothing more than a collection of data and functions that are grouped together.  If we were to compare JavaScript to the English language, objects would be nouns.  A function is a piece of code that does something - a behavior if you will.  Functions are the verbs in JavaScript.  Properties are the characteristics of objects.  To continue our analogy, properties are adjectives - they describe objects.

You create objects in JavaScript by writing functions that take properties as arguments.  To create a house object, for example, you might write a function that looks like this:

function house(color, numRooms) {
this.color = color;
this.numRooms = numRooms;

If you've done any Java programming, you'll notice that the above function closely mirrors a constructor.  The above function declares that a house object could be created that has two properties: color and numRooms.  When you call the house function, it expects you to supply the color and the number of rooms.  It then takes the properties you specify and assigns them to the properties.  Call the function like this:

house1 = new house("blue",8);

The above code creates an 8-room blue house.

Finally, knowing that an objects methods are also properties is important.  You can assign a method to a property by writing a separate function that does something and assigning it to a property name.  Suppose you write a function called paintHouse like this:

function paintHouse(color){
this.color = color;

You could then modify the house object to include the method:

function house(color, numRooms) {
this.color = color;
this.numRooms = numRooms;
this.paint = paintHouse;

You could then use the method like this:


You've just painted your house red!  You may have noticed the JavaScript keyword "this" in the above code.  Simply put, the "this" keyword refers to the current object.  For the paintHouse function, this stands for whichever house makes the call to paint itself.  In our case, the calling object is house1.  When we tell house1 to call its paint() method, it calls the paintHouse function to do the work.  Since house1 made the call to the function, this stands for house1.  If another house object, house2, calls its own paint method, then this would stand for house2.  The result is that the paintHouse function can paint any house by telling the individual object to paint itself.

The Nitty Gritty

As we've told you before, JavaScript contains many of the constructs that other programming languages contain.  Following you will see a series of tables that describe these constructs as they relate to JavaScript.


Operators come in two flavors: unary and binary.  Binary operators are usually the more familiar to people as they require 2 operands (the things to operate on).  Most folks have been using binary operators since they were small children.  An example is addition (+).  Addition requires two numbers to add together and is therefore binary.  Unary operators only require a single operand and the operator can come before or after the operand.  The ++ operator is an example.  The ++ operator simply increments a variable by 1.




The = operator is used in JavaScript for assignment.  The expression on the right is first evaluated then the result is assigned to the variable on the left.


These are shortcut assignment operators.  In programming, many times you must apply mathematical function to a variable and then assign the results to the same variable.  You can do this the long way like this:

x = x*8;

or use a shortcut like this:


The results are identical.  Remember how assignment works, the right side is executed first, then assigned to the left.


These are the math operators and they are identical to those you grew up with.  The % operator (modulus) may be new to you.  The % operator returns the remainder after doing division:

x = 17%5;

A value of 2 is assigned to x as 5 goes into 17 3 times with 2 leftover.


These are the comparison operators.  The == operator checks to see if two things are equal (remember, the = operator does assignation).  The ! symbols stands for "not" so != means "not equal".  Less than(<), grater than(>), less than or equal to(<=), and greater than or equal to(>=) mean what you think they do.  All the comparison operators work identically as in you algebra class.

&&, ||

These are the Boolean operators.  && stands for "and" while || stands for "or."  In order for a Boolean expression that contains && to be evaluated as true, ALL of the parts must evaluate to true.  In order for a Boolean expression that contains || to be evaluated as true, only ONE part must evaluate to true.  Here's a quick example:


(x<y)&&(y>z) //evaluates to false - y isn't greater than z
(x<y)||(y>z) // evaluates to true as x is less than y

String Operators

All of the comparison operators work on Strings.  The results depend on standard lexicographical ordering and are not case sensitive.  In addition, you may use the + operator on Strings to concatenate them.

Control Structures

Control structures allow you to specify what expressions get executed and when or how many time they will be executed.  These include conditionals and loops.  JavaScript provides two conditionals and two looping structures.



if(boolean exp)

The simple if statement determines whether the block of code following the conditional will be executed.  If the Boolean expression evaluates to true, the block will be executed.  Otherwise, the block will be skipped.

if(boolean exp)

The if...else construct supplies a block of code that will be executed if the Boolean expression evaluates to false in the else clause.  So, if the condition is met, carry out the first block.  Otherwise, carry out the second block.


The for loop carries out the same block of code until the test condition evaluates to false.  A simple example to write numbers to the screen might look like this:

document.write('Count is ' , count);

The above prints the numbers 0-99 to the screen.


The while loop executes the same block of code until the test condition evaluates to false.  You could re-write the above example with a while loop like this:

document.write('Count is ', count);

Take great care to create test conditions that will eventually evaluate to false.  You wouldn't want to freeze your user's browser as it quickly runs out of memory!

JavaScript Reserved Words

JavaScript contains a list of words that you cannot use in your scripts.  These words are reserved for JavaScript itself:
























































Because JavaScript is case sensitive, you could use Final in your script as that is different than final.  My advice, however, is to NEVER do this as it will just confuse matters.  Stay away from the reserved words in your scripts when choosing identifiers.  It will make your life much easier!.