Teach Yourself Programming


People keep asking me about how to learn programming. Before Steve Jobs killed it, Apple's HyperCard was by far the best way to learn programming. There never has been anything like it before nor since, but it only ran on classic Macs. Before Microsoft killed VisualBasic(v6) and replaced it with a completely different (and incompatible) product with the same name, VB6 was a reasonable second for people with lesser computers. Both of those are gone now, and they can't run on current computers anyway.
 
 

I started to write 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)

A distant third place is JavaScript. It's free and runs on all modern computers . There are numerous free JavaScript tutorials, but their focus is on making web pages interactive -- which is what JavaScript was designed for -- and that may be good and useful, but it's not what I have in mind. JavaScript is in fact a complete programming language. Like HyperCard and early versions of Basic, it is interpreted, so you can make changes and try again quickly. That's useful, because most of programming is about making mistakes and trying to figure out where. God gets His creation perfect ("very good") on the first cut; the rest of us debug our work, over and over.

This tutorial is designed to teach programming. Programming is hard work, and not everybody has the patience and attention to detail to do it well. If you like the discipline and the rush you get from doing something other people cannot, you will eventually want to graduate to Java and/or C++ but that takes money. JavaScript is free. Start here.

Although there are other and better programming languages, C/C++ is the language of choice for major software development (see my essay "C++ Considered Harmful"). If you want to program for pay in the world today, you must do it in C++ (or Java, which is very similar but not usable for some tasks). JavaScript is also similar to C++ so if you are careful not to do the things I warn you against, you can move to C++ or Java quite easily.

In this first page we will look at the smallest elements of a program, the constants, variables, and operators. Then we will look at statements and how to form them into larger structures. In the following section we will look at the largest structures, called functions. A program is generally a collection of functions, with some startup code. After that we will look at complex data structures, and how functions are associated with them in what is called Object-Oriented Programming, or OOP. Later we will do some game programming and animation.

This tutorial is a work in process. Lately I have been uploading revisions every few days. Most of the files have revision dates at the front or end, which you can check to be sure you have the latest copy. This entire tutorial (including supporting files) is also available in a single zip here.
 

Getting Started

Programming is a profession, and professionals need tools. Software tools are programs that help programmers do their job. For JavaScript you need only two: a text editor (like NotePad) and the interpreter itself (which is the browser you are reading this in). NotePad is not the best text editor, but you will find it easier to use for writing JavaScript than Word, because Word assumes (in this case incorrectly) that you want styled text, and you must keep turning that feature off. Programmers often pay for fancy text editors that have the features we find useful, but such features are frills; buy one when you know what you want. If you are as careful as I am about viruses (which technically JavaScript is) then you must enable it in your browser , but most people don't worry about it and the default is enabled, so you are good to go.

Most of the free JavaScript tutorials start with a long explanation of where and how to place your scripts in the HTML page. Because that is not our purpose here, I will give you a simple template to use. Read one of the other tutorials if you want to get fancy.

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 it. The first and last lines will be unchanged; 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 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) then open it in your browser. Usually that is as simple as double-clicking the file icon, but 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. If it didn't work, you may need to get somebody to help you. Once it's working, the rest should come along without bothering your favorite guru again.

From now on, you will replace that one middle line with whatever complicated program we have concocted from time to time, leaving the top and bottom lines in place. Usually there will be one or more "document.write()" lines with something inside the parentheses, which lets us see the results of the program running. This is called "output". JavaScript is not real strong on input, and besides, it's not what programming is all about, so we won't worry about it at this time.

Most of programming is about finding the mistakes you made, and the JavaScript interpreter in your web browser is not very friendly, so I wrote my own. Read about it here (we'll get to it later).
 

Component Parts

All computer programming languages have certain essential ingredients. You need to understand them to write programs. These are constants, variables, and operators, which combine to form expressions, and then statements, and finally structures. The largest structure is a program. We'll discuss structures later.

Another important part of programs is the comment, which doesn't affect how the program runs in any way, but is often helpful for explaining to other programmers (and especially to yourself, tomorrow) what this part of the program is intended to do. One-line comments begin with a double slash // and end at the end of the line. Block comments start with /* and end with */ possibly on another line and/or in the middle of the line, with executable code resuming after the comment. Comments can occur anywhere a space is permitted. Here are some examples of comments:

document.write("Hello world!"); // this is a comment
// document.write("Hello world!"); // this whole line is a comment
/* comment at front */ document.write("Hello world!");
document.write/* comment in the middle */("Hello world!");
/* this is three lines of comments,
   including all of this..
   and ending at the end of this line */
Constants are values that cannot change when the program is running, and you can tell they are constants because they (mostly) look different from variables. Variables hold values temporarily, and the program gets interesting when variable values are changed from time to time. Operators combine constants and variables into expressions, which have their own transient values.

Numbers and quoted string literals are the most obvious constants. 1 and 3 and -27 and 3.1416 are numerical constants. The quoted strings "Hello world!" and "3" and the empty string "" also constants. Other constants such as true and false look like variables.

You can experiment with constants in your program. Try replacing the "Hello world!" literal with another constant, then save it and click the Reload button on your Test window in the browser, or if there is no such button, the View->Refresh menu. The Reload/Refresh is necessary because most browsers make a copy of the file, then look at the copy instead of the (possibly changed) original. Closing the window and re-opening it seems to work in Windows. If nothing shows at all, you probably made a typing mistake. Check your work very carefully, or else go back to something known to work, then make your changes one at a time, checking each modification. See also Debugging JavaScript.
 

Variables

A JavaScript variable name is written as a single word containing only letters and digits (no punctuation except the underscore "_" which is considered to be a letter), and starts with a letter. In C and JavaScript, capital letters are considered different from lower-case letters. Many programmers depend on that and define separate names that differ only in capitalization, but I consider that a Bad Idea, because when you speak the name you cannot pronounce the difference, so it results in avoidable programming errors. Fixing errors is the hardest and most time-consuming part of programming, don't make it harder than necessary.

Other items in JavaScript look like variables in form (we already saw true and false) but aren't. Some of these are reserved words (like true and false) which can only mean what the language has defined them to mean. The rest of them are programmer-defined identifiers, which mean whatever you, the programmer, want them to mean (within the bounds of the language). That's part of the buzz of programming, you get to be a god -- not Almighty God, who makes the rules -- with you controlling your own little part of the universe. Within the rules, of course: you can't color outside the lines, your program won't work if you do.

In most programming languages (including JavaScript), values have one of a small number of predefined types, or else a programmer-defined type. JavaScript is weakly-typed, which means you don't have to worry about it much. It would be a god idea to get used to thinking about types, because adult languages are much more finicky about types. You also can get some surprizes (also known as "bugs") if you pay too little attention. The three basic JavaScript types are string, number, and boolean (true and false). Most programming languages further subdivide numbers into integer and floating point (with a decimal point), but not JavaScript. Data structures form their own types, which in OOPS languages are called classes. Classes in JavaScript are pretty hokey (different from C++ and Java), so we will mostly avoid them, but we'll say more about that later.

JavaScript variables are untyped, which means they can hold any value of any type, and the interpreter figures out what to do with it at runtime depending on the type of value last given to it. This is great and convenient for small programs, but bigger than a few hundred lines it tends to lead to all sorts of hard-to-find bugs. Types are your friend.

Because they are untyped, JavaScript variables can magically appear the first time you put something into them. After that, they hang around until the program ends. In adult languages like C or Java, you must tell the compiler what type the variable is, and then you can use it only for that type of value. You should get into the habit of using each variable for one type only, to avoid frustrations when you graduate to the big leagues. You should also explicitly create your variables, using the reserved word "var" at the front of the line where you first give it a value. If you don't, strange things may happen (which might just be a bug in the interpreter on my computer).

To put a value into a variable, you need an assignment stament. We'll cover the other statements later, but assignment is simple. The name of the variable comes first, followed by the assignment operator, then the value, finally ending in a semicolon, for example:

myVar = 3;
It is tempting to pronounce the assignment operator as "equal" but that's not a good idea, because there is another "equal" operator for comparison. I prefer to say "gets" as in "myVar gets three" for the statement above. This captures the meaning of the assignment statement, which is to put the value 3 into the variable myVar.

Variables are like mailboxes in the postoffice or at the front of an apartment. The mail carrier comes and puts values (letters) in the boxes. Sometimes they get a letter in the wrong box, and take it out and place it in a different box. Unlike mailboxes, variables can hold only one value. Unlike letters, the same value can be put into several variables. As the program runs, new values can replace old ones, so each box always has a value, but it changes from time to time, as directed by the assignment statements.

We now expand our test program to two lines (notice the variable declaration):

var myVar = 3;
document.write(myVar);
Try it. Try giving different values to the variable. Try spelling the variable differently. Notice that if you don't spell it exactly the same in both places, you get no output at all. That's because JavaScript made a second variable for the different spelling, but that new variable had no value (perhaps an empty string).
 

Operators

Now we can learn about and experiment with the operators. You already know about plus and minus from grade school. For numbers they mean the same thing in JavaScript, add and subtract. Multiplication uses the asterisk "*" and division uses the slash "/" symbols for historical reasons, but they work pretty much the way you'd expect from grade school. Try:
var myVar = 3;
document.write(myVar+2*5);
Notice that the multiplication was done before the addition, the way we learned in school. If you want the calculation to happen in a different order, use parentheses to group the operations that must happen first:
document.write((myVar+2)*5);
This is called operator precedence. You can experiment with other numbers and operators to get the feel for it. You can also build an expression value on the right side of the assignment statement, provided you use only constants or variables previously defined. The variable is not defined until you put a value into it, and the interpreter in my browser gives it the cryptic value NaN (Not a Number) if you try to use an undefined variable. But you can define multiple variables, then mix and match:
var myVar = 3;
var x = 5+myVar;
document.write(x*2-4/myVar);
There is a fifth numeric operator % invented for C and preserved in JavaScript, which does an integer divide but returns the remainder rather than the quotient. Thus (5%3) has the value 2. In C and Java there is a difference between integers and floating point numbers (which can be fractional or very large); (5/3) is always an integer divide in those languages, with a value 1, whereas in JavaScript it has the fractional value 1.6666... If you really want an integer divide in JavaScript, you can use a subterfuge like subtracting the remainder before dividing: ((5-5%3)/3). As I said above, it's a complete language, even if you must spell some things strangely.

Negative constants look a little strange inside expressions, because the negative operator is spelled the same as the subtract operator, but has a different precedence in C and its derivatives (including JavaScript). This means bizarre expressions like (3+-2) or (3- -2) make perfect sense in JavaScript (note the space: "--" is a different operator, which we'll get to later). You can use spaces (or new lines, including comments) anywhere except within an identifier or a number or a 2-character operator (spaces inside a string literal are of course part of that string). We could also put all three statements on the same line, but it would be harder to read. C programmers sometimes like to brag about how much their "one-liner" programs can do, but it's a false bravado.

There is only one string operator, concatinate, and it's unfortunately spelled the same as the add operator. I guess the language designers were thinking that it's essentially adding the strings together, but concatinating strings is fundamentally different from adding numbers. Thus "Hello"+World" has the value "HelloWorld". This gets weird when your strings have numeric values: "3"+"2" is the string "32" but "3"-"2" is the number 1. That's because the interpreter does its best to make sense of what you gave it. The plus makes sense for strings, so it concatinates them; minus is only valid on numbers, but the strings can be converted to numbers and then subtracted. Notice that ("3"+2) is still the string "32" and "3"-2 still makes sense as having the value 1. Try different combinations of values and operators to see how this works.

There are three boolean operators, logical AND (&&), OR (||) and NOT (!). NOT inverts false to true and vice-versa; (a&&b) is true only if both a and b are true, and false otherwise; while (a||b) is false only if both a and b are false, and true otherwise. The bitwise operators & and | and ~ work the same on the individual bits of numbers. Thus 5&9 gives 1, while 5|9 gives 13, and ~5 gives -6; the exclusive-OR operator ^ gives 0 where the bits match, and 1 where they don't:

  0101     0101     0101
& 1001   | 1001   ^ 1001   ~ 0101
  0001     1101     1100   111010
If you use a numeric operator on a boolean value, the interpreter converts the value to a number, 0 for false, 1 for true. There are also the (numeric) bit-shift operators, left-shift << and right-shift >> which you can experiment with. If you are not good at working with binary numbers, you probably won't have much use for these at first. Eventually you will need to become familiar with binary numbers if you are going to be a successful computer programmer.

There are six comparison operators, which compare any two values and give a boolean result. If the values are not the same type, they are converted to something that is, boolean to number, and if it can, string to number, otherwise number to string, but it's not a good idea to depend on this automatic conversion, because grown-up languages don't do that. The operators:
 
== equal   != unequal
   < less than >= not-less
 > greater than <= not greater

Hierarchy

All of the operators are in a complex precedence hierarchy, like we saw for addition and multiplication, but I can never remember what it is (and the Sun JavaScript specification doesn't say, but I found it here), except that negation comes before multiplication and division, which comes before addition and subtraction, which comes before comparison, and that logical AND comes before OR (but not necessarily after comparison, where should have been). Any other combinations of operators -- and especially logical operators with anything else -- the order should be explicitly specified with parentheses. Extra parentheses don't hurt.
 

Assignments

Recall that I called the assignment symbol an operator. The designers of the C programming language considered it a full operator, which can have bizarre side effects. JavaScript continues this insane tradition, but you should avoid using it for other than assignment statements. The interpreter will not complain if you do something foolish like this:
var myVar = 3;
document.write(myVar=5);
but you might be surprised to see the result (5, rather than false), and even more to discover that the next time you use myVar it has the new value. C programmers are proud of doing stuff like this, which is one of the reasons C code is so much more fragile than better languages. I don't recommend it.

There are two other operators, which like the assignment operator, have persistent side effects. These are the increment ++ and decrement -- operators. They are useful in their place, and you can make your code especially unreadable by using them elsewhere. The expression (++myVar) increments the variable by +1 before it is used in the value of whatever expression contains it, and (myVar++) increments it after it has been used. The decrement operator works the same, but subtracts 1 from the variable. Notice that the variable retains its new value. I personally refuse to use these operators inside expressions, because they are the unwitting cause of so many bugs. Like assignment, you can use the increment and decrement operators in their own statements, thus:

myVar++;
--myVar;
Of course it makes no difference whether you put the operator before or after the variable name in this stand-alone usage; most people use the postfix form (after). Note that every statement ends with a semicolon, with one exception we will get to later. Using the increment operator can be thought of as shorthand for an assignment. These two statements have exactly the same effect:
myVar++;
myVar = myVar+1;
When you are incrementing part of a data structure, and if you used something with side effects in determining which part to increment (not recommended) then the second, longer form could give a different result. In any case, it might take slightly longer, but speed is not a big worry with interpreted languages like JavaScript. Most C++ compilers recognize these two statements as equivalent and generate exactly the same machine code, so there is no difference at all.

There is a third way to say the same thing, which is the plus-assignment operator:

myVar += 1;
There are corresponding combinations of most of the operators, which allows you to update a variable by their respective operations and any appropriate value. I don't clutter up my memory with these extras, as they do not contribute anything useful to my programming skills.

Next: Statements

Tom Pittman
Rev 2010 December 24