Welcome to Goetz's Programming Kit v 1.0

Copyright 1998 Lawrence Goetz

You'll find lots of JavaScript tools I've made for you to carry out basic tasks, such as from getting information from a person at the computer, to displaying information on the screen. Within a short while you will be writing your very own JavaScript programs.

The functions for use with Goetz's Programming Kit

All these functions and code will make more sense when you read the section on programming.

get("statement")

Returns a text input from the keyboard. The statement is a question or statement that you ask the person at the computer to enter in. Use this when the information the person enters is not to be used in any mathematical way. For example a persons name would be used here. If cancel is pressed, null is returned.

An example of code:

var name=get("Please enter in your name")
display("Your name is "+name)

This example will ask for someone's name and then display.

getnumber("statement")

Returns a number input from the keyboard. The statement is a question or statement that you ask the person at the computer to enter in. Use this when you want to get a value used in arithmetic. If cancel is pressed, 0 is returned.

An example of code:

var total

var number1=getnumber("Please enter in a number")
var number2=getnumber("Please enter in another number")

total=number1+number2
display("Your total is "+total)

This example will ask for two numbers and then calculate the total and display the result.

getdecimal("statement")

Returns a number with a decimal point input from the keyboard. The statement is a question or statement that you ask the person at the computer to enter in. Use this when the number entered contains a decimal. For example when dealing with currency or temperature. If cancel is pressed, 0 is returned.

var price=getdecimal("Enter in a price, but do not enter in the $ symbol.")
var discount
var discounted_price

discount=price*.10
discounted_price=price-discount

display_newline("Your item originally priced $"+price)
display_newline("is now $"+discounted_price+" after 10% off.")
display_newline("You saved $"+discount+"!")

This example will ask for the price of an item and then display the original price, discounted price, and amount saved.

letter(string,at)

Returns the letter at a location in a string. Use this if you want to look at the contents of the letters of a word or sentence.

var word="Hello"

display("The first letter of "+word+" is "+letter(word,1))

lowercase(string)

Returns the string in lowercase. Used in a compare when you don't care about the case.

Example

var word1="HELLO"
var word2="hello"

if(word1==word2)
        display_newline(word1+" and "+word2+" are equal.")
else display_newline(word1+" and "+word2+" are not equal.")

if(lowercase(word1)==word2)
        display_newline(word1+" and "+word2+" are equal.")
else display_newline(word1+" and "+word2+" are not equal.")

At the first compare it will say they are not equal, because it sees that the case is not the same, although the words are the same. In the second compare it looks at the lower case and there it matches.

display("statement")

Displays a statement on the screen in the output box.

This example will display the text:
Hello world.

display("Hello world.")

display_newline("statement")

Displays a statement on the screen in the output box and goes to the beginning of the next line. Like a carriage return on a typewriter.

This example will display to the screen:
Hello world.
Hello again.

display_newline("Hello world.")
display("Hello again.")

display_clear()

Clears the output box.

pause()

Pauses the program. A window pops up and asks to continue. Use this when you want to display something on the screen and then wait before displaying something else.

display("Hi there.")
pause()
display_clear()
display("Welcome back.")

This example will pause between the display statements.

printer("statement")

Prints a statement to the printer's window.

This example will send to the printer window:
Hello world.

printer("Hello world.")
printer_done()

printer_newline("statement")

Prints a statement to the printer's window, but adds a new line in a similar way display_newline("statement") works.

This example will send to the printer window:
Hello world.
Hello again.

printer_newline("Hello world.")
printer_newline("Hello again.")
printer_done()

printer_skipline()

Use this when you want to skip a line on the printer.

printer_done()

When you are finished with the printer, you must call this function. It will write the information to the printer window. When you wish to print out the information you must go to the printer window and press Ctrl-P in Windows, or Apple-P on a Mac. The printer window should automatically be brought up for you when you call this function.This also sets up a clear for the printer window, so that when you print again it prints to a clear window first. Please do not close the printer window until you are done using your program completely. If you close it and you wish to run your program again you may get an error message and need to restart your browser.


You'll need a text editor, such as Notepad or Wordpad that comes with Windows. I never used a Mac, but I guess they have a text editor as well. Even a word processor that can save as plain text will also work. Your browser should handle JavaScript. This version of my programming kit only works on Netscape. It failed to work on my version of Internet Explorer. You will also need to have JavaScript enabled for the programs to work. If it is not enabled, you can enable it by going to:
Options, Network Preferences, Languages, then make sure JavaScript is checked.

You are actually writing JavaScript, and you can use any JavaScript commands you like. You might want to get a book or look on the internet for JavaScript information. You'll find lots more things to do in JavaScript if you refer to another information source. I just cover the basics in this kit.


Programming

To begin your program, you'll need to define a function called main. A function is a group of code that the computer will work on. It needs to know where to start and will look for a function called main. Think of main as the main part of your program. Here is what a blank function of main would look like.

function main() {

}

You start any function with the keyword function. This lets JavaScript know that you are defining your function. The next word is the name of the function. You can never have any spaces in a function or variable name. I'll get to variables shortly. Next you have ( ), this means there are no arguments to the function. An argument is like a command or option. I'll speak of arguments momentarily. The { } define the beginning and end of the function.

Now that you have a function defined, lets make it do something. The most basic of programs is the Hello World example. This will display Hello World on the screen. There is a function that I have written for you that will display anything on the screen. The function name is called display. It takes as an argument the item or group of items to get displayed. In this example you would write.

display("Hello World")

Notice that there is a " at the beginning and a " at the end. This tells the display function that the argument getting passed to it is a string. A string is a group of characters. It will then display those characters on the screen.

There is also display_newline which will display a line of text and then go to the next line of the display. This is like a carriage return on a typewriter. It takes the same argument as display.

So your first program should look like:

function main() {

        display("Hello World")

}

Indenting is not required, but it makes the code easier to read.

Save your file as a text file and give it the extension .js . For example call your code myprog.js . I've even enclosed a file called myprog.js which contains a blank main function to help you out.

In the file goetzkit.htm I've set it up to look for that file name. If you want to give your program another name than myprog.js you need to edit a line in goetzkit.htm to find your program name. Find the line:

<SCRIPT LANGUAGE="JavaScript" SRC="myprog.js">
</SCRIPT>

If you named your file something other than myprog.js, change myprog.js to whatever name you called your .js file.

You can optionally change the title of the page by changing:

<TITLE>Goetz's Programming Kit</TITLE>

You might also want to make a copy of the goetzkit.htm file for each program you write and then rename it to the name of your .js file. So you could copy and rename the file myprog.htm .

You will need to have goetzkit.htm, goetzlib.js and myprog.js all in the same directory.

Now that you have done that, you are ready to run your program. Open in your browser the file goetzkit.htm or myprog.htm (if you renamed it). You can open it by doing Ctrl-O on the Windows version of Netscape. Then press the BEGIN button. If you followed everything so far you will see in the output box the words:
Hello World

You can send output to the output box, a printer window, or to an alert window.

I have included 3 examples. They can be found in the subdirectory examples in the directory that this document is in.

Simple:
welcome.htm  -  displays a welcome message on the screen. The source file is welcome.js .

A little more complicated:
hello.htm  -  asks for your name and displays a hello message with your name in it. The source file is hello.js .

Complex:
shopping.htm  -  a shopping cart program to add up prices and print a receipt. The source file is shopping.js .


Variables

A variable lets you store information in the memory of the computer. For example:

var year=1998

var is a keyword that tells JavaScript you are setting up a variable in memory. The variable name in this case is called year. The = assigns year a value. The value assigned in 1998.

You can now display the value.

display("This year is "+year)

Notice that display will get more than one item to be displayed. The + sign means concatenate, or join, the statements together to form one big string. You might be asking yourself "Isn't year a number?". Yes it's a number, but when it gets displayed it gets displayed as text.  JavaScript does lots of automatic things for you. Also notice that year doesn't have a " " around it. This is because you are not displaying the word year, but the value in the variable year.

You can get input, or information from someone at your computer with the get function.

var name=get("What is your name?")

This sets up a variable called name. It is assigned the value gotten from the get function. The get function received as it's argument the statement to tell the person at the computer, so they know what to enter.

Now that you have gotten the name, you can display it.

display("Hello "+name)

There are 2 other get functions. getnumber and getdecimal. Use these when the value you are getting from the person at the computer is a whole number, or a number that contains decimals respectively. You'll find more information on those in my functions listing.

Now that you have a number you can do some calculations with it. You'll find a calculating example in my functions listing.

You can do mathematical expressions.

var answer=5+10+15

display(answer)

This will display 30 on the screen.

You can increment a value by doing ++ to the name and decrement a value by doing -- .

var number=10

number--

display_newline(number)

number++

display_newline(number)

This will display 9 then 10.


if else

You can test variables and perform different actions based on the value. These are if and else conditions. You test to see if a condition is true. If it is true, then you do what's inside the if's {} signs. If it's false it does what's in the else {}.

var number=10

if(number==10) {
        display("number equals 10")

}

else {
        display("number does not equal 10")

}

Notice that when you compare a value, you need to have a double equal sign. A common error is to write only one equal sign. If that happens you will be assigning the value of 10 to number and it will always be true.

Try changing the value of number and see what gets displayed.

You can do more than one kind of compare.

a < b     a less than b
a > b     a greater than b
a <= b   a less than or equal to b
a >= b   a greater than or equal to b

You can even compare strings using greater than or less than. JavaScript bases this on their location in alphabetical order.
if("dog">"cat")
This expression is true, because dog is higher in the alphabetical listing than cat. However capital letters are less than lower case letters so:
if("Dog">"da") is false because Dog begins with a capital letter.

logic commands

|| or           a || b        Either statement a or b has to be true.

&& and    a && b   both a and b have to be rue.

! not                        Take the inverse of the truth value for an equality.
                               c!=10 mean it's true if c is not equal to 10.

if(number==10) {
        display("number equals 10")

}

else if(number<10) {
        display("number is less than 10")

}

else {
        display("number is greater than 10")

}

else if means if the previous if wasn't true, see is this if is true. When you have the else if, it only checks the ifs until one is true and skips testing the rest. If you have multiple if statements is a row, it will check all if statements.

if (something) {

}

if(something else) {

}

You can have many if statements. Here it will check both if statements and do things for each one that is true.

If you only have one statement in the {} you don't need to write the {}. You'll notice I left off the {} in an example when I explain my functions.


Loops

For loop. If you want to have a piece of code done more than once, you can use a for loop.

for(some initial value;truth statement;update command)

Another way of looking at it is.

for(i=some initial value;i<=some ending value;i++)

Here is an example:

for(i=1;i<=10;i++) {

}

This will do something inside the {} 10 times. i is a variable that starts out equal to 1. Each time it's checked to see if i<=10. If that is true you keep doing the instructions in the {}. Each time you finish the instructions in the {}, i increments. The first time it checks the loop condition i=1, i<=10 so it goes through the loop once. At the end of the loop i is incremented to become 2. The loop is checked again and i<=10 so it goes again. The last time checking the loop i=10 and it goes through the loop. When the loop gets to the end, i becomes 11, but 11 is not less than or equal to 10 so the loop exits.

for(i=1;i<=10;i++) {

        display_newline(i)

}

You may need to scroll down the output box to see the rest of the display.

This will display the numbers 1 to 10 on the screen.

Another kind of a loop is a while loop.

while(something is true) {

}

example

var i=1

while(i<=5){

     display_newline(i)
     i++

}

This will display the numbers 1 to 5. It will keep doing the code in the {} as long as i is less than or equal to 5. The i++ keeps incrementing until i is 6 and the loop exits. If you forget to place the i++, then i is always less than 5 and your browser will lockup, because it is in an infinite loop. You will need to do an End Task if that happens. In Windows, that's Ctrl-Alt-Del and choose your browser as the task to end. I don't use a Mac, so I don't know it's command.

In while and for loops you can use any kind of condition for testing for true. It doesn't need to be only <= . You can have < . In the for loop if you want to use > or >= then you need to start at a value greater than the ending value and decrement the value by using value--. An example:

for(i=10;i>0;i--) {
display_newline(i)
}

This example will display the numbers 10 to 1 in reverse order. It doesn't display 0, since it stays in the loop as long as i is greater than 0.

Just as in the if and else statements, you can leave off the {} in loops if they contain only one statement.


Functions

With functions you can make your own operations for tasks that you do a lot. You write a function like you did for main, but here you fill in the ( ). Plus a function can return a value.

For example an adding function

function add(a,b) {
       var total=a+b
       return total

}

return tells JavaScript to return a value. You can only return one item per function. This function receives two arguments, a and b. Notice the comma , separating them. add adds the arguments up in a variable called total and then sends back total's value.

You'd have in your main code what looks like this:

var amount=add(15,25)

display(amount)

This will display the result of adding 15 and 25, which is 40.

There is a scope or range of a variable. If it's declared inside a function, only that function knows about it. If you declare it outside the function it's global and any function can refer to it. If you pass a variable to a function, it can not modify the value. A way around this is to make the variable global and pass no arguments. This way you can edit the value and after the function is done, the value is changed.

For example the original a and b remain unchanged after calling this function. This is because the function works on a copy of a and b.

function add(a,b) {
       var total=a+b
       a=0
       b=0
       return total

}


Misc. Stuff

alert("Message") lets you have a pop up window to notify the person at the computer.

confirm("Message") returns a true or false value, depending on whether the person presses OK or Cancel. You can use this in your while loops to keep getting information until the person presses Cancel.

var x=11/5      x will equal 2.  5 goes into 11 two times.
var x=11%5    x will equal 1.  5 goes into 11 two times but there is 1 left over.

x+=5      adds 5 to whatever x was equal to. You can also have:
x-=5       subtracts 5 from x.
x/=5       x becomes whatever x divided by 5 is.
x%=5     x becomes the remainder of x divided by 5.
x*=5      x becomes x times 5.

* in programming is multiply.  y=5*6   y will be 30.

Also the order in which the expression is evaluated goes by the order of operations of math. For example 2+5*3 will be 17 not 21. If you wanted 21, place ( ) around the operation you want done first. (2+5)*3 will now be 21.

JavaScript commands are case sensitive. So Display is different from display.

Special printing characters:

\n is the new line character. So if you want to display in the alert function on
multiple lines you can do:

alert("Hello\nWorld")

For the printer, the \n doesn't do a new line, you'll need to use the printer_skipline() function to skip a line on the printer.

\t is the tab key. So if you want to indent something do:

alert("Hi\tthere")

If you need to use special characters such as " ' or \ you'll need to add a \ before them. So to display those characters you'd need to do \" \'  or \\ . Example:

alert("I\'m a programmer.")

Output Box:

In the goetzkit.htm file you can change the size of the output box to get more room if your monitor setting is larger than 640*480 resolution. You can edit the numbers on this line:

<TEXTAREA NAME="Output" ROWS="6" COLS="50" wrap="hard"></TEXTAREA> <BR>

COLS value is the number of characters left to right.
ROWS value is the number of characters top to bottom.

If you make the values too large it will not fit on the screen.

When an input window, alert window, or any other window appears while running your program, you can move it. Left click on the blue title bar of the window that just appeared, and while holding the mouse button down, drag the window to view the output box.


Advanced stuff

You can create objects, since JavaScript is object oriented. Here is a sample. You can find more in books or online.

function entry(name,number) {
        this.name=name
        this.number=number
}

This defines an object called entry. It has 2 variables, name and number. To use it you do the following:

var person= new entry(name,number)

You'd fill in the name and number with a value, or ask the person at the computer to enter in the values and pass them as an argument. new tells JavaScript this is a new instance of entry and it builds it based on the values passed to it.

var person=new entry("Information","555-1212")

You can refer to the variables by doing:
person.name
person.number

display(person.name+" "+person.number)

You can add delays to operations by using setTimeout("command",millisecond delay)

You place a command inside the "" and give a delay in milliseconds (1/1000) of a second. 1000 milliseconds is 1 second. For example if you want to display something after 1 second you can do:

setTimeout("display('Hello World')",1000)

Notice that there is a single quotation mark ' used where there would be a " in the normal way of calling display. This is because you are using "" in the setTimeout function and it would confuse the system seeing a "" inside itself.

You should note that your program will continue to run after that line of code. This will not pause your program for 1 sec and then run that command. It's best used in a function to keep calling itself and display an animation. This will make an animated display.

var words= new Array()

words[0]="Welcome to"
words[1]="Goetz's Programming Kit!"
words[2]="By Lawrence Goetz"

var i=0

function animation() {

        if(i==words.length)
                 i=0

        display_clear()
        display(words[i])

        setTimeout("animation()",1000)
        i++

}

function main(){
      animation()
}

Arrays

An array is a group of variables in the same location in memory. They have an index number. For example you can have a group of entries using the object I showed before.

var people = new Array()

people[0]= new entry("Information","555-1212")
people[1]= new entry("Someone else","555-1234")

people.length tells you how big the index is. In this case, people.length is 2. It begins with 0 as the first entry, but you can start with 1 if you like; however then the total will be 3. The length appears to be the largest index number that you entered plus 1.

You refer to the array by giving the index number. So display(people[0].name) would display Information.

null statement

null is a special value given to an item with no value. For example in the get function if someone presses cancel you will be given the value of null. You can use this to test to see if someone entered a value by comparing the variable to null.

var name=get("Enter a name")

if(name==null) {
        display_newline("You didn't enter in a name")
}

For the getnumber and getdecimal a 0 is returned if no number is entered.


Comments

You can place comments in your code so you know what you are doing.

// is a comment. The double slash tells the browser to ignore anything on that line.

// This will display on the screen Hello world.
display("Hello world")

You can also comment out many lines by doing /* to begin a comment and */ to end a comment.

/* This will display on the screen
Hello World
*/

display("Hello world")


Error Messages

If you make a mistake in writing the program you will get an error message when you run it. Study the message. It will tell you what line of your code and where on the line the error is.

If you refer to a variable that was never given a name you will get an undefined error.

var number=5

// It will say that numbee is undefined.
display(numbee)

You will also get error messages if you forget a ( , " or other symbol. Also if you misspell a function name you will get an error.

When you get an error message you must click ok on it's window. If you don't click ok but you instead click the browser window, your browser will appear to be locked up. This is because it's waiting for you to press the ok on the error window. If this happens, switch back to the error window and press ok. If you get more than one error, you will have to repeat this for the other windows. It's best to click ok on the error windows before returning to your browser.


Help

I recommend "JavaScript for Dummies" published by IDG Books. It's found in many book stores and has a lot of great information. Some of what I learned for this kit, I learned from that book.

Sites on the internet:

JavaScript 411

JavaScript Frequently Asked Questions

Learning JavaScript via Windows On-line Help

JavaScript Documentation from Netscape


Suggested programs to write

Now that you have seen how to write programs, here are some suggested programs you can create:

Experiment and see what other programs you can come up with.


Send suggestions, corrections or comments to:
goetz@dorsai.org

If you find this programming kit helps you write programs, please show your appreciation. I'd very much like a picture postcard of your city, state or country as a way of saying thanks. Please send it to:

Goetz Programming Kit
Lawrence Goetz
3263 Bedford Ave.
Brooklyn, NY 11210
USA


Visit my web site for more programs that I've made. As well as to check to see if I've revised this kit.