Intro to the intro
At one time in college I briefly considered becoming a computer science high school teacher. I found myself helping people around me quite a lot with CS homework and things, and it was pretty rewarding when it worked out. At another time, I tried to tutor a friend in CS, but I don't think I was patient enough, and didn't really have the right materials. I think I'll try again. This is an experiment.
This is not meant to be a tutorial in learning how to program. There are plenty of sites on the internet that will do that for you, with varying degrees of success. This is supposed to be an introduction to computer science. CS encompasses a few things other than simply programming. It also includes algorithmic thinking and understanding how computers work. Rest assured, learning how to program is an integral part of it. In fact, that will be our starting point with this...lesson. I guess that's the best word for it.
I should mention that I am using some CSE142 courses from the University of Washington for some of my reference and probably for programming problems.
The primary language I want to use in these lessons is Javascript. Javascript (or JScript as I may call it from time to time), is--as the link points out--a misunderstood language. It has a lot of expressive power, but also has a simple syntax with the added benefit of looking quite a bit like C/C++ and Java. In that respect, you could call it a gateway language. Har!
What is a program?
The core thing of interest in CS is a program. A program is just a series of instructions for the computer to do. You are telling the computer what to do, and in what order to do it, and it does it. Computers are hard workers, but fairly stupid, so it's up to you as a programmer to be very explicit about what steps you want it to take. That's what programming is about.
Programs are written in text files. You can use any text editor, like Notepad, to create or edit a text file, and then use that file as a program. But not all text files are programs. For that to happen, the contents of the file has to conform to a language. A language describes how the computer should interpret the contents of your text file as a program. Enough talking; let's see what a program looks like!
WScript.Echo("Hello World");
The conventional first program to write in any language to test it out is one that prints out the text, "Hello World", for some historical reason. If you create a new text file with just that single line in it, save it in c:\hello.js
, and run it (on a command prompt) by using the command cscript c:\hello.js
, you should see this output:
Hello World
You might be able to kind of sort of read that program as though it were English: echo "Hello World". For "echo", think, "say back to me." Now to clarify the various things that are going on with this program.
I said earlier that a program is a series of instructions. A better term for "instruction" is statement. A program is a series of statements. In this example, the hello world program contains just one statement. A statement is an instruction telling the computer to do something. When you run a Javascript program, the computer goes one line at a time from top to bottom through your file and does each line in order.
Programs also contain expressions. An expression is something that results in a value. Statements in a program can contain expressions that indicate more about what the computer should do, or how to do it.
Before I get into this next sample program, I need to point out one thing. If you see //
, it is known as a comment. The computer ignores everything on the line following it. It's used to write additional clarifying information alongside code. Note that this can be used on its own line (the line begins with //
, and so the entire line is ignored) or on the end of a line (the line has some code that is executed, and then //
, so only things after the //
are ignored).
// statement
WScript.Echo("Hello World");
// expression
WScript.Echo("Hello World");
As you see above, the text between the parentheses is an expression. The program is instructing the computer to Echo
(that is, print out or output for the user to see) some text. The text to print out is an expression, which has the value "Hello World".
Other miscellanea about this particular example. WScript
is not too important right now; just know that it's necessary and will be explained later.
Blank lines do nothing in a Javascript program. You can insert as many blank lines as you want in between any two lines of your program and receive the same result. For example, the following two programs do exactly the same thing.
WScript.Echo("Hi there");
WScript.Echo("Hi again");
WScript.Echo("Hi there");
WScript.Echo("Hi again");
Generally speaking, most statements in Javascript end in a semicolon. This rule and others comprise the syntax of the language. The syntax of a language is the set of rules that you must follow when writing your program so that the computer can interpret what you wrote. In English, if you neglected all punctuation, used the wrong punctuation, or put punctuation in strange places, someone else may have a hard time understanding what you mean. Likewise, if you do not adhere to the syntax of a language, the computer cannot run your program, because it can't understand you. Unlike humans, the computer is fairly unforgiving about syntax errors, and will usually just display an error message when you try to run your program, rather than try to guess your intent.
Other things from our example that are part of the syntax include the fact that pieces of text need to be enclosed in double quotes (""). The fact that blank lines are ignored and that comments (using //
) cause the rest of the line to be ignored are also part of the syntax.
Functions, your best friend
Echo
above is what is known as a function. A function is a group of statements that are executed together. That group of statements is called the function's body. When you use a function, the computer jumps to the first line of the function's body, does each line in turn until the end of the body, then jumps back to the next line where you were before.
I said, "use a function" in the previous paragraph. The proper term is calling, or invoking. These terms describe instructing the computer to jump to the function's body, run all of the lines in it, and jump back to the next line after the invocation.
In the example program above, you called a function named Echo
. The body of that function happens to be in a different file, so you can't see it. Later, you will see functions whose body is visible to you. You should imagine that on the line that says WScript.Echo("Hello World");
, the computer jumped to the function body of Echo
(not visible to you), did several lines of program there, then jumped back.
One of the most important features of functions is that they can act on different data whenever called. In the following example (a new program), you are calling the same function, but supplying different data.
WScript.Echo("Hello");
WScript.Echo("Goodbye");
On both lines, the function being called is the same: Echo
, but on the first line the data supplied is "Hello"
, whereas on the second line, the data supplied is "Goodbye"
. The same type of activity will take place on each line--displaying some text--but the specific text being displayed will be different.
I mentioned "supplying data to a function" a few times in the previous paragraphs. The proper term for the data being supplied is argument, or parameter. The more conventional term for "supply" is pass. So instead of "supplying data to a function", we say pass an argument to a function.
Briefly going back to syntax, function call arguments are always enclosed in parentheses, and immediately follow the function name.
Creating your own functions
One of the most important parts of programming is that you can define your own functions. The way you do this is by using the keyword function
followed by the name you want to give to your function, the parameters that someone is allowed to pass to the function, and the function body. The body is enclosed in { }
(curly braces), which is part of the syntax of the language and tells the computer where the body starts and ends.
Just to quickly review, remember that the parameters are the pieces of data that someone can supply when calling a function. And remember that the function body is the set of statements that are run, in order, when something calls the function.
Here is an example in which I have defined a function named Greet
, then called it. You can write or paste this code in a new text file and save it as c:\greet.js
. Then you can run it on the command prompt like you did before with hello.js
, by using the command cscript c:\greet.js
.
function Greet(person)
{
WScript.Echo("Hello, " + person);
}
Greet("Owen"); // output is: "Hello, Owen"
There are a lot of interesting things about this example. On the very first line, I defined the function, which consists of what I said in the previous paragraph--giving the function's name, parameters, and body.
After the end of the function body, I call the function and pass a parameter to it. The parameter's value is "Owen"
. At this point, the computer jumps into the function body, to the line that says WScript.Echo("Hello, " + person);
. The computer runs this line, which causes "Hello, Owen" to be displayed. Then the computer goes to the next line, but that is the end of the function body, so it jumps back to where it was before--the line after Greet("Owen");
. Since this is the last line in the file, the program is done.
There's one crucially important detail here that I need to point out. This is one of the most difficult, fundamental concepts to grasp, so I will try to explain it thoroughly. When you pass an argument to a function, it can be used within the function body. In the example above, the argument "Owen"
that you pass to Greet
can be referred to within the function body as person
. As we will see later, various different things can be passed as arguments to the function. No matter what, the code within the function body can always refer to the value that was passed in using the name person
. One simplistic way to think about it for now is that everywhere you see person
in the function body, the computer automatically substitutes the data that you passed as the argument.
By the way, You may be able to surmise from the example and code that +
here appends one piece of text to another.
As you will discover later, using functions is one of the primary ways of breaking down a large problem into smaller pieces.
More on function definitions
I'd like you to try something with your greet.js
example. I'd like to delete the last line, save the file, and run the program again. What do you see? You should see nothing at all, but why is that?
Remember that there were two steps that I explained in the example: defining the function and calling it. By deleting the last line, you removed the function call but not the definition. This should tell you that defining functions has no visible side effect. Just because a function with a certain name, parameters, and body exists doesn't mean that anything really happens. Only when it is called does the contents of its body run. You could define a million different functions; so long as you don't call any of them, your program will basically do nothing.
Variables, a constantly useful construct
Sometimes you need the computer to remember a piece of information. This is the purpose of a variable. A variable is a holding place for a piece of information.
We can use an analogy that a computer is like a building full of storage units. Each storage unit is empty and unused initially, but could be reserved by someone and used to store something. If the computer is the building, a variable is a little bit like a storage unit in the building, and your program is the customer who can reserve rooms.
When you declare a variable, you reserve a place in the computer that can be used to store data and give a name to that place, so that you can refer to it later. In the analogy, declaring a variable is like reserving a storage unit and picking a unique name or number for the room. Now you have an empty space that could be used to store something, and you know the room number so that you can get back to it later.
When you assign to a variable, you store an actual value in it. In the analogy, this is like putting some of your stuff in the storage unit. You use the room number to find the unit, then put something in there, then carry on with your life, knowing that your thing will stay in there until you take it out.
Finally, you can read a variable, which retrieves the value that you stored in it previously. In the analogy, this would be like going to the storage unit (again, using its room number to find it), and looking at what's inside. The analogy breaks down a little, because you don't actually take anything out of the room at this point.
Here is a new program that you can save and run. In it, we declare, assign to, and read a variable. Let's save it in c:\variable.js
and run it.
// declare a variable
var someName;
// assign to a variable
someName = "Owen";
// read the variable by using it
WScript.Echo("Nice to see you, " + someName);
// output is: "Nice to see you, Owen"
There are a lot of things going on here that are important to know. The way to declare a variable, according to the syntax of the language, is to use the var
keyword, followed by the name you want to use for the variable.
The way to assign to a variable (store something in it) is to use the variable name, followed by =
, followed by the thing you want to store in it. In this program, I've stored a piece of text in this variable for later use. After the line reading someName = "Owen";
the value "Owen"
will be stored in the variable named someName
.
Finally, in the Echo
line, we are reading the variable, simply by using its name in an expression. The expression it is used in is "Nice to see you, " + someName
. As part of computing the value of that expression, the computer sees the variable named someName
and reads its value (what you stored in it before) to substitute into the final piece of text.
More on function arguments
I'm going to combine parts of a greet.js
and variable.js
into a new program, as follows. Let's save it as c:\greet2.js
and run it.
function Greet(person)
{
WScript.Echo("Hello, " + person);
}
var someName;
someName = "Owen";
Greet(someName); // output is: "Hello, Owen"
There's one very important point that you need to understand here. Notice how when we define Greet
, we write person
as the name of the parameter, and refer to that data by the name person
in the function body. And then notice that we wrote the line Greet(someName);
. Well, someName
doesn't "match" person
... but it doesn't have to!
On the line where we call Greet
, the computer determines the value of the parameter before that value is passed to the function body. So by the time the computer gets into the function body (the Echo
line), it doesn't matter what we wrote outside of the function. The function body only knows that it was passed an argument that it knows as person
.
A simplistic way to think of it for now is that Greet(someName)
is automatically transformed by the computer into Greet("Owen")
when the program runs.
That's one of the great powers of functions. No matter what expresion you pass to them, the data is available within the function body by referring to the same parameter name within. Similarly, you have freedom to pass any expression to the function as an argument, and the function will be able to handle it, so, for instance, you're not restricted in what you name your variables.
Exercises and solutions
To see whether you've understood any of this, here are a series of sample programs that make use of some of these constructs. If you've understood well, then in the comments where I ask what the expected output is, you should be able to guess exactly what the output should be. Each code block below is a separate, complete program that you could save in a text file and run with cscript, but try to guess the output before resorting to that.
// problem 1
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
Func1("abc"); // what is the output?
Problem 1 solution - click to show or hide
Func1 abc
// problem 2
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
var text = "def";
Func1(text); // what is the output?
Problem 2 solution - click to show or hide
Func1 def
// problem 3
function Func2(text1, text2)
{
WScript.Echo("Func2 " + text1 + ", " + text2);
}
Func2("aaa", "ddd"); // what is the output?
Problem 3 solution - click to show or hide
Func2 aaa, ddd
// problem 4
function Func2(text1, text2)
{
WScript.Echo("Func2 " + text1 + ", " + text2);
}
var text1 = "abc";
var text2 = "def";
Func2(text2, text1); // b) what is the output?
Problem 4 solution - click to show or hide
Func2 abc, def
// problem 5
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
function Func3(text1)
{
Func1(text1);
}
Func3("def"); // what is the output?
Problem 5 solution - click to show or hide
Func1 def
// problem 6
function Func2(text1, text2)
{
WScript.Echo("Func2 " + text1 + ", " + text2);
}
function Func4(text1)
{
Func2(text1, text1);
}
var text2 = "rrr";
Func4(text2); // what is the output?
Problem 6 solution - click to show or hide
Func2 rrr, rrr
// problem 7
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
function Func5(text1, text2)
{
var text3 = text1 + " " + text2;
Func1(text1);
Func1(text3);
}
Func5("dep", "ped"); // what is the output?
Problem 7 solution - click to show or hide
Func1 dep
Func1 dep ped
// problem 8
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
Func1(""); // what is the output?
Problem 8 solution - click to show or hide
Func1
// problem 9
function Func1(text1)
{
WScript.Echo("Func1 " + text1);
}
var text1 = "efg";
text1 = text1 + text1;
Func1(text1); // what is the output?
Problem 9 solution - click to show or hide
Func1 efgefg