Teach Yourself:

Programming in JavaScript

Introduction

This course teaches computer programming. More precisely, this course helps you to teach yourself computer programming. Like bicycle riding and piano playing, you learn programming by doing it. But it helps if you can get pointed in the right direction. That's what this course is for.

You can expect to learn how to program your computer in a particular programming language called JavaScript (also known as ECMAscript). I designed this course both for people who want to learn computer programming in general -- where JavaScript is merely the first step before you move on to other programming languages like C++ or Java -- and also to a lesser degree for people who might already know one or more of those other languages, but need to know JavaScript in order to control a web site.

This course assumes only that you know how to type, copy & paste, and navigate the internet in a browser. If you are reading this, you probably already have these basic skills. If you already know how to program some other programming language like C++ or Basic (but not JavaScript), some of this course material will seem elementary, but you can skip over the parts you already know how to do.
 

I started this tutorial when I thought somebody would use it. That didn't seem to happen, so I stopped working on it. If you really want to use this, convince me, and I'll try to bring it up to date. Or maybe I'll just point you at my later effort to teach people to Learn Programming in Java. (TP 18June26)

On Programming

Programming is not mathematics, and math skills are not normally needed to be a good programmer -- unless you want to make mathematical software. A little grade school arithmetic is sometimes helpful, but not often. Much more important is the ability to think clearly. Programming is nothing more than telling the computer in a special language and in excruciating detail how to do what you yourself already know how to do.

There are several layers in telling a computer how to display a web page. At the top, somebody must decide what content to display, and then how to order it and what it should look like. At the bottom of the heap is the hardware that presents pixels to the viewer, and just above it, the software that converts text and images to pixels. These lower levels are outside the scope of this course, because all software (not just web page display) depends on them.

Somewhere in the middle of this layered heap of responsibility is HTML, a language for telling the computer about paragraph and font management, and which also identifies links to other pages and the placement of graphic elements like tables and pictures. HTML tells the computer what to display, and gives it in the order to be displayed, then the browser software in the next layer down decides exactly the pixel positions and such details. HTML can be thought of as a programming language for displaying the contents of a web page, but it lacks the ability to make decisions, so nobody calls it "programming"; it's just data. There are computer programs to convert ordinary text and pictures into HTML, which the client browser then converts back into text and pictures -- or rather pixels, which the viewer sees as text and pictures. It's all done automatically by magic. The technical term "magic" means "I'm not telling you how it happens."

Higher up in the hierarchy of responsibility, closer to the person with the authority for making decisions about what to display, is where JavaScript lives. You can display web pages with no JavaScript involved at all, just the person creating (or using a commercial program to create) HTML, which is sent out over the internet to each browser displaying that page, where it is shown to the viewer. But that can be a lot of work, and most web pages depend on variations in the data the client wants to see. The page designer cannot be sitting there making these choices in real time as each user calls up that page, so we program computers to make the decisions. Originally, and still mostly, it's software inside the web page server doing the work. JavaScript offloads some of the work onto the client computer. JavaScript can also be used (still in the client computer) for manipulating and verifying the user input before sending it to the host.

JavaScript is a programming language for controlling how a web page looks and behaves. It is related to HTML the way animals are related to plants: both are a form of computer programming, but like plants, HTML can't go anywhere; JavaScript can move around (make decisions) on its own. However, just as all animals depend directly or indirectly on plants for food, JavaScript must depend on HTML to get it going and to implement the final display. This course does not teach everything you need to know about HTML to make beautiful web pages, but only enough to make JavaScript work. There are other courses (here and elsewhere [links TBA]) for learning everything there is to know about HTML. You don't need to take them before learning JavaScript, we will cover right here in this course everything you need to make JavaScript work (which isn't much).
 

Tools

You will need some (software) tools to program a computer, but you can easily get what you don't already have. Computers only understand the ones and zeroes of binary numbers, and most programming languages require specialized software tools called a "compiler" or "interpreter" for converting the human-readable programming language into what the computer understands. The computer you are reading this on already has that tool for JavaScript, it's in every web browser.

Unfortunately, Microsoft bungled their implementation, and while Internet Explorer can interpret the JavaScript we will be working with, they won't let you test your own code locally. You can, but they make it difficult. If you already use a different browser, you are good to go. Otherwise, you might want to download and install one to the other browsers, like FireFox or Google Chrome. Your scripts will probably still work in IE through the internet, if you are careful.

You also need a simple text editor. Many programmers use fancy (and possibly expensive, but not usually) text editors, which have been specially designed to make programming easier. If you have one of those available, that's great, but you don't need it. WordPad will do fine (on Windows, TextEdit on OSX is usable, but only after some unobvious contortions; if you are on Linux, you already know and use a text editor).

Another useful tool is a debugger, so called because it helps you to step through program execution to find errors (called "bugs") and subsequently remove them. Debuggers tend to be tricky, hard to use, and/or expensive. I never used somebody else's debugger when I learned JavaScript, but I did eventually write my own. You can use it free with this course, but it's awkward in Internet Explorer and the FireFox debugger FireBug is in some ways better. More on that later.
 

Art & Engineering

Programming is an Art, something like architecture. Like architecture, you need to know something about How Things Work. An architect might want to design a building that floats above the ground with no visible supports, but the laws of physics do not permit such a building to exist, and the architect who wants to get paid for his work must know things like that. Usually architects pay engineers to tell them what can and cannot be done. Programmers must be their own "engineers" and programming is sometimes called "software engineering" because of that. But engineers only do things they know how to do. Artists do things that have never been done before. We can only write computer programs to do the things that we know how to do (because programming is telling the computer how to do those things), but we strive to make programs that have never been done before. Programming is thus both engineering and art.

Unlike the painter and the architect, the programmer's art is mostly never seen by other people. If an architect designs ugly buildings, nobody will buy his designs, but if a programmer designs ugly software, so long as it works, who cares? Like a child's finger paints, your first efforts at programming will not be "beautiful" but if you stay with it, you can design masterpieces.

Some things the users of your software will see. If it is abusive to the users, or crashes the computer, they will scream and cuss you out. Don't do that. We'll talk about ways to prevent those unfortunate outcomes later.

Unlike the other arts -- even architecture -- programming is an exercise in power. Real power consists in making people & objects do what you want. If you are very rich, you can pay them to do those things. Money is power. A skilled painter or musician draws emotions out of people. The great artists of the past did that; now the artists seem content with evoking shock. Shock and awe, both are emotions. The power of programming is different. Programming gives you absolute control over the computer, and if done well, considerable control over the people who use those computers. Programming is an awesome power. We focus here on controlling the machine; what you do beyond that is up to you.

The greatest power anybody can exercise consists in enabling your subject to make good decisions on their own. That's what programming is, telling the computer how to make those decisions -- in advance, before you know what the data is that the program will be processing. It takes a lot of concentration for really complicated software, but you can do it. This course will get you started learning those skills. If you want to.
 

Lesson 0

In another place I explain why zero is the first number. It's a geek thing, and you might as well get used to it. There are good technical reasons for it, but they really don't apply to lesson numbering. Except that this lesson is more of a preface to learning programming.

It is traditional for beginning programmers that their first computer program says "Hello world!" and then quits. It's not much of a program, but it's a start. We will do that now.

First we must deal with the mechanics of getting your program into the computer so the computer can run it. Open WordPad (or your favorite text editor) and type the following text into it:

<html> <head> <title>JavaScript Test</title> </head> <body> <script>
document.write("Hello world!");
</script> </body> </html>
If you are lazy like me (and I suspect most programmers), you can also copy and paste the three lines, it's faster and you make fewer mistakes. If you are using Internet Explorer you need another line to get past that pesky blockage, so you have four lines instead of three:
<html> <head> <title>JavaScript Test</title> </head> <body>
<!-- saved from url=(0014)about:internet --> <script>
document.write("Hello world!");
</script> </body> </html>
The extra line is ignored by the other browsers. For most of this course, you will keep the first (or first two) and last lines unchanged; only the middle line (between the <script> and </script> tags) is the actual program that we will be changing all the time. This is the traditional one-line "Hello world!" program that all C programmers begin with. Later, when we get into "Object-Oriented Programming" (OOPS), I'll explain what "document.write()" means, but for now you can think of it as a way to see the results of your program.

To run your program, you need to install it into a web page. Everything you need is already there, just save the file as "Test.html" (without the usual ".txt" at the end). Most text editors will try to add that ".txt" so the operating system knows to open it in the text editor next time; you don't want that. If you use a formatting editor like WordPad or Word, it will try to save it as a formatted document (".rtf" or ".doc" or some such); you really don't want that. When you choose the "File->SaveAs" menu, it will put up a dialog box where you type a file name. Next to the file name is also the format it should be saved in. The default is almost always wrong, you must pop up the menu to choose "Plain text". It may not give you the choice to eliminate the ".txt" in the file name, but this is not catastrophic, just an extra step. You can save it in your default Documents folder or on the desktop where it is easy to find.

If you succeeded so far, you will see the file on your desktop with the browser  icon, so you can open it by double-clicking the file icon. You can also open it within your browser from the File->Open menu. If everything went well, you should see the "Hello world!" message as a single line of text in the new window.

But things go wrong. Mostly you will make silly mistakes that you didn't notice, and the program won't run. Sometimes (but not today, not using JavaScript) it might even crash your computer. Maybe the mistakes are obvious and easily fixed, other times it can take hours or days to figure out what went wrong. It comes with the territory, get used to it. Later we will discuss ways to find those elusive bugs, but it still takes time.

Check the file name of the file you saved. You need to see the whole file name, including the extension, to verify that you spelled the extension correctly. If not, click on the file name and "Rename" it to have the correct extension. Windows will ask if you really want to do that. You do.

If you made a typing mistake, the program won't run. This is why I recommend copy and paste. Some people imagine themselves to be very good typists, but everybody makes mistakes. The computer will not tolerate any mistakes. None at all. Even the "good typists" spend a lot of time on the backspace key. Plan on it.

The video for this lesson goes through the process. After your first program works, you should try making changes and see what happens. That way, when you make that kind of mistake, you will recognize the problem and (maybe) know what to fix.
 

HTML Lesson 1

Now we are ready for your first HTML lesson (out of three). The text inside the parentheses (and quotes) of the "document.write()" line is HTML. That's the whole lesson. JavaScript produces HTML and feeds it little by little through "document.write()" commands to the browser, which displays it. If you already know HTML, you can experiment with feeding metatags to the display this way. If not, don't worry about it, we'll get there soon enough. Here is an example of using the Bold metatags:
document.write("Hell<b>o</b> world!");
If this is all JavaScript did, why bother? Just write HTML directly.

The difference, as we will learn in later lessons, is that you can program conditionals and repeats in JavaScript. You can even construct the text which is displayed from information that is not displayed, such as by doing arithmetic on the numbers, or using them to control the position of things. This gives you a lot more control on how things appear. Try this experiment, by replacing only the middle line of the existing program with these two lines:

document.write("The sum of 2+2=";
document.write(2+2);
Notice that there is no numeral "4" in the text we gave it to display, JavaScript did the arithmetic. What's inside the quotes is presented (as HTML text) to the browser to be displayed; the arithmetic operation is calculated before display.
 

Six Program Elements

Every programming language has some way to do six essential things that programs need to do. Different languages spell these things differently, but they all do them. JavaScript was designed to resemble C++ and Java for most of these things, so once you know one of these languages, it's easy to transfer your skills to another one of them. Other languages can be very different, but they still do these same six things:
 
1. Sequence, doing steps in a particular order;

2. Assignment, calculating and holding values for later use;

3. Conditionals, making a decision on the basis of a value test, then doing either one step or another (but not both);

4. Iteration, repeating a sequence of steps multiple times;

5. Functions (also called "methods"), giving a name to a sequence of steps, then calling on that function from different parts of the program; and

6. Input and output (I/O), transferring data from the external world into the program, and getting results back out.


JavaScript is by design rather weak on (I/O). For output we only have HTML display in the browser window, or changing the data in a form sent to the page server computer. Input is even weaker, and limited to extracting the data from a form, which the user put there. Most languages (including JavaScript) do their I/O using function calls, so the differences are easy to learn.

JavaScript functions are slightly different from C/C++ and Java, but everything else is pretty much exactly the same. I will mention the differences as we encounter them, so you can use JavaScript as a learning tool for C++ or Java without getting hung up on the differences.

We will look at how to do these six things in JavaScript over the next six lessons, then move on to higher-level abstractions, the real meat of programming. The remainder of this course is devoted to exercising your skills in credible examples of JavaScript in use: some form data validation, a simple data obfuscator to foil spammers, stuff like that. We end up with several larger programs: some stand-alone games, and finally an extended discussion on the design and operation of my JavaScript debugger, which is written entirely in JavaScript. See you there!