Chapter 2

How to talk to a computer

Let’s get started. You’re going to need two applications to start programming. The first is a web browser: the very same program that you’re using to read this web page. Perhaps it is Chrome or Firefox or Internet Explorer or Safari. Any of these will work fine.

Text Editors
The next program you will need is called a “text editor”. This is one of the simplest programs you can have on a computer, and you already have at least one. It’s not the same thing as a “word processor”, which is what you use to prepare a document for printing. A text editor is even simpler: it doesn’t have any formatting, fonts, tabs, paragraphs, titles, or any of that stuff. All it does is handle plain old everyday text.

Programmers use text editors for their work, and so there are some truly astounding (and rather expensive) text editors out there that can do all sorts of powerful things that only programmers need. Any text editor that you have to pay money for is too powerful and will only confuse you. For now, stick with the simplest text editors. Fortunately, the simplest of all are built right into your computer. For the Macintosh, the built-in text editor is called, amazingly enough, “Text Edit”. The built-in text editor for Windows is called “Notepad”.

Your first program
Here is your very first program:


<!DOCTYPE html>
<html lang="en-US">
<head>
	<title>My JavaScript</title>
	<meta charset="utf-8" />
	<script>
		var myCanvas, context, window, document;

		window.onload = function() {
			myCanvas = document.getElementById("splashScreen");
			context = myCanvas.getContext("2d");
			context.textAlign = "center"
			context.font = "36px Georgia"
			context.fillText("Hello World", 500,50);
		};
	</script>
</head>
<body>
	<canvas id="splashScreen" width="800" height="600"></canvas>
</body>
</html>

Copy this text and paste it into a new document in your text editor. Then “Save” the new document to your desktop with the name “Test.htm”. Now go to the desktop and double-click on that document. It should open up in your browser, showing a black window with the words “Hello World”. Ta-da! You have written your first program!

Playing with the program
Now comes the part where you really start to learn: play. I want you to play with this program by altering different parts of it. Of course, you’ll need to know what all this means, so now I’m going to explain each line of the program and what changes you can make to it. You open the document in your text editor, change it in some manner, then you save it. At this point, your browser will still be showing the previous version of the document; to see the new version, double-click on the document itself.

<!DOCTYPE html>
This line of code tells the computer that this document is an HTML document. You must not mess with this line; leave it exactly as it is.

<html lang="en-US">
This line tells the computer that you’ll be using American English in this document. That helps it figure out some things. Don’t mess with this.

<head>
This tells the computer that you are beginning to tell it certain information that isn’t actually part of the body of the document; the information that you’ll be presenting next will apply to the document as a whole. This section will be ended with the line </head>. Nope, you can’t mess with this line, either.

<title>My JavaScript</title>
At last, a line that you can play with! This line specifies the title of the page; that’s the text that you see above the contents of the page. For example, the title of this page (the one you’re reading) is “Chapter 2 | Interactive Storytelling Tools for Writers”. You can replace “My JavaScript” with anything you want. Go wild! Try “Rutabaga” or “Programming is fun!” or “Joe Blow is a Stinker” or even something naughty. The computer doesn’t care.

Do NOT, however, alter anything OTHER than “My JavaScript”. Do not touch the <title> or the </title>. Those are required. Leave them alone!

<meta charset="utf-8" />
Don’t touch this line, either. It tells the computer that you want everything written in plain, ordinary text. If you want to use Chinese, Arabic, or some other alphabet, I think you change this. I’m not sure, because I’ve never tried to write things in other alphabets.

<script>
Another no-no. This tells the computer that the stuff that follows is all written in the JavaScript language. It means “Computer, up until now I’ve been talking to you in the HTML language, but now I’m going to talk in the JavaScript language. I’ll tell you when I’m done talking JavaScript and am going back to the talking in HTML.” 

var myCanvas, context, window, document;
Here is our first line of JavaScript code. It says: “OK, computer, I’m going to be using four variables with these four names. Get ready to use them.” 

You, of course, ask, “What is a variable?” A variable is just a box inside the computer that holds data. It can hold any kind of data you want. It can hold a number like 27. It can hold words like “Hello World”. It can hold all sorts of other stuff. I’ll explain some of this other stuff as we come to it.

You could rename any of these variables, but if you give it a new name in this line, you must similarly change its name in all other places that it appears in the program. It’s always a good idea to give a variable a name that tells you something about what it means. Don’t ever use silly variable names like “lemon”, “apple”, and “orange” (unless of course, your program is about fruit). Try to make each variable name as descriptive as possible.

window.onload = function() {
Actually, this is NOT the next line in the program; there’s a blank line that I skipped over. The blank line means absolutely nothing; I put it there to make the program a little easier to read. THIS IS IMPORTANT: because it can be so difficult to figure out where a program is screwing up, it’s always a good idea to use little tricks like this to make it easier to read. The blank line makes it easier to separate the variables from the function. The tab spacings are also a good way to keep straight what lines do what work. 

OK, so let’s take apart this line of code, piece by piece. The first word is window. This is a standard variable (box) that holds the information about the window in the browser that your program is using. Think of it as meaning “the place where we’re putting visual information like words, numbers, and graphics.” 

Next, there comes a period. That’s important! It means that the thing after it belongs to the thing before it. In this case, it means that onload belongs to window. This brings up one of the features of JavaScript that’s both nice and nasty. JavaScript provides you with all sorts of special tools that can do wonderful things for you. That’s nice. But in order to use them, you have to memorize them. That’s nasty. It’s like any language: you have to learn a lot of words before you can start speaking the language. 

In this case, onload means “this is what I want you to do when you first get started.” It’s a function (the next word). A function is a little chunk of JavaScript that does something. You might wonder why the word function is followed by a pair of parentheses. Take heart: that’s something you don’t need to learn just yet. 

Next comes a curly brace all by itself. In almost all programming languages, curly braces enclose a number of lines of code. They specify that all the lines of code inside them is to be treated as a single chunk — they’re all executed together, in sequence. If you look seven lines further down, you’ll see the curly brace that closes the chunk. That means that there are six lines of JavaScript code in this chunk. And this chunk is meant to be executed when the page is first loaded into the browser. In other words, it is executed first thing.

myCanvas = document.getElementById("splashScreen");
This is the first line of code in the chunk. It’s complicated. I’ll start with the equals sign “=“. That doesn’t mean “equals”. It really means “take whatever is on my right and put it into the box on my left.” It would make more sense if it were an arrow like this: <=  or this: <—, because that gives you a better idea of what it means. In fact, some languages use an arrow instead of an equals sign. It’s just one of those stupid things about computer languages. It’s just like the fact that the word “knight” is pronounced “nite”. It makes no sense, but that’s just the way it is.

So this line tells the computer to take document.getElementById("splashScreen”), whatever that is, and put it into the box myCanvas. So what is it? 

Let’s start with document.  That’s another special word in JavaScript that you just have to look up in the JavaScript dictionary. It means “this document” — the file that you made. The whole thing. 

You already know that the period means that the thing after the period belongs to the thing before the period. So document has something called getElementById. If you look this up in the JavaScript dictionary, you’ll discover that it means “get the thing with an id called ‘splashScreen’”. So the line of code means: “Look through this entire document for something that has an id of ‘splashScreen’”. By the way, “id” is just computerese for “identification”. 

Sure enough, if you look down near the bottom of the code, you’ll see this: 

<canvas id="splashScreen" width="800" height="600"></canvas>

It must be what we’re looking for. So our line of code says, “Get the canvas below and store that in a box called myCanvas

At this point your are entirely justified to throw your hands up in exasperation and demand to know why the code has to take such a roundabout route. I will not answer that question because the answer is absurdly complicated. It’s just one of those things like the fact the past tense of “sing” is “sang”, but the past tense of “bring” is “brought”. Get used to it.

context = myCanvas.getContext("2d");
Here we go again with another apparently arbitrary line of code. The only reason we needed to get myCanvas in the line of code just above this was so that we could use it in this line of code. And the only reason we’re getting context is so that we can use it in the next four lines of code. 

By the way, I might as well tell you about that silly little semicolon “;” tacked on to the end of the line. It means “this is the end of the line of code”. Once again you might wonder, isn’t it obvious that this is the end of the line of code? Anybody can see that! In this case, I can explain the reason why we use a semicolon to mark the end of the line of code. Sometimes you have to write an extremely long line of code, a line so long that it runs right off the edge of the window. In that case, you want to hit RETURN and break the line of code up into shorter pieces so that you can read it. But then the computer would be confused about where the line of code ends. So we put a semicolon at the end to say, “Yes, indeed, this is definitely the end of this line of code.” 

Don’t mess with this line of code.

context.textAlign = "center";
Now at long last we’re getting down to business: this tells the computer: “OK, for the context that I have previously established, I want you to use center-alignment for the text, not right-alignment or left-alignment.” This tells the computer to put any text in the center of the window. Once again, we’re relying on special words from the JavaScript dictionary.  You can change “center” to any of the alignment styles listed when you search the Web for “JavaScript textAlign”.

By the way, you might be wondering about this JavaScript dictionary to which I keep referring. Where is it, you ask? Well, there are a number of such dictionaries. There is an official one, but it is written in formal computerese that you will never understand. It is the only genuine “dictionary”; the stuff that you need to learn about can be found with Web searches for phrases like “Javascript reserved words” or Javascript syntax” or “Javascript functions”. The problem is that there are a zillion of these and you usually have to look them up for a very particular problem. Isn’t this fun?

context.font = "36px Georgia";

This tells the computer what font and size to use. You can change the 36 to anything you want; try different numbers here. However, I do not recommend that you attempt to change the font itself; that gets us into complicated stuff. Later.

context.fillText("Hello World", 500,50);
Here at last we actually do something! This tells the computer to draw the text “Hello World” into the window at the position (500, 50). That position is measured in pixels; the horizontal coordinate comes first and the vertical component comes second. Coordinates are measured from the upper left corner. So the text will be drawn 500 pixels from the upper left corner and 50 pixels down.

Try changing those numbers. You can move the text all over the window. Of course, if you use coordinates that fall outside the window, then the words won’t be visible. So if you use (5000, 50) or (-500, 50) or (500, 10000), you won’t see the words. You can also change the text itself. 

};
As I mentioned earlier, this line merely closes off the function() specified earlier. This is the end of the function.

</script>
This marks the end of the JavaScript. It means “OK, computer, I’m done talking in JavaScript; from here on I’ll resume talking in normal HTML.” 

</head>
This markes the end of the header of the web page. It means that we’re done talking about things that apply generally to the entire page.

<body>
This marks the start of the explicit content of the web page. Usually this would have all the pictures and text that would appear on the page. But we cheated: we put the text in a JavaScript program in the header. We can use either method, but the JavaScript approach gives us much more power, which we’ll be using later on.

<canvas id="splashScreen" width="800" height="600"></canvas>
I’ve already talked about this line. It says “Make me a canvas (that’s a special JavaScript word), call it “splashScreen”, and make it 800 pixels wide and 600 pixels high.” You can change the id of the canvas, but if you do, make certain that you change the reference to it above. You can also change the width and height, but it won’t make much difference because they’re so much bigger than the text you’re writing (“Hello World”).

</body> 
This tells the computer that we’re done listing the contents of the body of the web page.

</html>
This tells the computer that we’re done talking to it. This is the end of the document.


Syntax Errors
Perhaps you have made some changes and everything went to hell. The screen didn’t show anything, or it was somehow really messed up. This is almost always the result of what is called a “syntax error”. 

Syntax errors are probably the worst problem for beginers. Did you notice that I misspelled “beginners” in the previous sentence? Perhaps, but it certainly didn’t even slow you down. You instantly knew what I meant to write, and you flew right past that mistake. Good for you!

Computers, alas, are not so forgiving. The tiniest misspelling, the slightest deviation from the required spelling will create a syntax error, which usually causes the computer to screw up. 

But computers aren’t the only ones to exhibit extreme sensitivity to syntax errors. In the right circumstances, people can be just as block-headed. How many times have you heard this line:

“We’re sorry, sir, but we cannot honor your request. You have not properly filled out form RC/22b, Authorization for Transmittal of Individual Confidential Information. Please review this form and fill it out completely and resubmit your application.”

If you think about it, this is really the same response as the computer’s syntax error. Both the computer and the bureaucrat respond to a communication that does not fit their required format with the same unyielding obtuseness.

Just to be fair, let me throw in another example:

"If the moment of inertia tensor is not diagonal, unstable perturbations will develop."

Does this sentence make any sense to you? You have no context with which to understand it. How else could you respond to it other than to throw up your hands and say "Syntax error!"?

Communication Responsibility
Whose fault is it in a case like this? Who has the responsibility for insuring that the communication gets through loudly and clearly? The speaker or the audience? We Americans, steeped in egalitarianism and a spirit of cooperation, tend to answer that both sides share responsibility for clear communications. I disagree, and I think that your experiences with computers will lend weight to my position. I think that the responsibility for clear communications falls squarely on the shoulders of the speaker.


In theory, the audience of a communication is supposed to give feedback to the speaker on how clearly the message is getting through. Thus, if you and I are conversing, and something I say doesn’t make sense to you, you are supposed to say, "Run that by me one more time, please." This scheme insures that our conversation will move smoothly and efficiently.

In the real world, however, this seldom happens. Sometimes the audience doesn’t want to appear stupid by asking a dumb question. Sometimes the listener believes that his confusion is temporary and will quickly abate. Sometimes the listener is so completely lost that he doesn’t even know where to begin. Whatever the cause, he just nods his head knowingly and mutters, “OK”.

How then can we communicate well if our audience can’t be trusted to speak up when it is confused? There is only one sure-fire solution, and that is to assume very little of the audience. You must be pessimistic, assuming that everything you say is lost on the audience. You must drive home every single point with ruthless drive and determination. You must be a defensive driver, imagining what is going on in the mind of the audience, trying to guess where they might be tripped up next. This is the only way to communicate with confidence.

It is a hard lesson to learn, but the computer provides an excellent training ground. It assumes nothing, knows nothing. It has no context with which it can second-guess what you really meant to say. It can respond to your commands only in their absolute, literal sense. It will indeed drive you crazy. But it will also discipline you to think hard about exactly what you say. It is a sobering experience to have so many of your commands rejected as syntax errors — you never knew you were so sloppy a communicator. But once you learn to express yourself clearly and carefully, you will find that the number of syntax errors you generate will fall.

The lesson you learn in the process will benefit you in many areas other than computers. Precise communications are important in almost everything we do. How many arguments have you endured that were started by a misunderstanding? How many foul-ups have you gotten into because somebody didn’t express themselves exactly? I well remember the time my father drove 30 miles to pick me up "at the Doggie Diner on Main Street". Neither of us knew that there were two Doggie Diners on Main Street. He went to one, I went to the other. If I had been more specific, the screwup would never have developed.

The most powerful demonstration of the crucial importance of precise communications is provided by an airline accident some years ago. As I recall, the tower had instructed the pilot, "Come down 3000". This was an ambiguous instruction; was the pilot instructed to come down to 3000 feet, or was he ordered to come down by 3000 feet? The pilot assumed the former, but the tower meant the latter. The pilot came down to 3000 feet; there was a mountain at 3200 feet; there were no survivors. Precise communications can be a matter of life and death.