JavaScript is a programming language developed with the purpose of running programs from web pages on the Internet. Javascript may lack some important elements to make it useful as a general purpose programming language, but it does contain most of the relevant elements found in a programming language and thus can be used for learning how to program.
Unlike most programming languages, Javascript does not require a compiler. Javascript programs are interpreted by most web browsing programs (Internet Explorer, Netscape and others). Therefore, if you have a browser, you don't need to by anything else to run Javascript.
Due to the fact that the code is interpreted by the browser, programs in Javascript are multi-platform. In other words: Your program may work without changes in a PC, a Mac, a Workstation or any other computer as long as you have a browser supporting Javascript.
Although most browsers support Javascript, this feature can be disabled in the browser. In order to run your programs, make sure that Javascript is enable in your options (or preferences).
Notice that, when you are browsing web pages, there are two special computers involved: the server and the client. The server is usually the remote computer that host the pages for a given web site; the server is the computer that you are working with. The web pages containing Javascript programs are in the remote server, but they are sent to your computer and that is where the Javascript runs: in your computer.
Programs in Javascript must be embedded in HTML pages. Inside the HTML page, you should signal the start and end of your script with the following:
- <script language=javascript>
- //... your program goes here ...
- </script>
Now, since your program must be embedded in an HTML page, you need at least the following:
- <html>
- <body>
- <script language=javascript>
- // your program goes here
- </script>
- </body>
- </html>
You may add html between the "/script" and the "/body"
The example below can show you this. If you click on this link, you will see a page that simply says:
Welcome to Javascript
You may see the html source of this by clicking "View -> Source" in your browser.
After you see the source, click back in your browser to return to this page.
Here is your link:
Note: comments
You can write comments anywhere in your javascript. All you have to do is to insert two slashes "//". The rest of the line will be ignored by the program and treated as a comment.
Comments are extremely useful in helping you develop and understand the program. Use the comments to explain what you are trying to do. The comments do not explain anything to the computer, but they explain to you and to other people that may have to understand or modify your program.
Notice that, in the above text there is nothing between the lines "your program starts here" and "your program ends here". This is because you really don't have any program yet. The message "Welcome to Javascript" was displayed simply using good old standard HTML.
Now you can start adding features to your program. Let us tell the computer to display an additional line of text in the page, so that the page will look like this:
Welcome to Javascript
We hope you enjoy this
Well, of course you could do that by simply adding another line containing "We hope you enjoy this" (Why not try that? go ahead!). You can, instead manipulate the web page by telling the web page document to write a line of text of your choice.
This is how you would do that:
document.writeln("We hope you enjoy this");
Pay attention to the format of this statement:
- document.writeln - Those two words are all in lowercase and separated by a dot. There should be no spaces or other signs.This tells the computer that you want to write a line of text in the current document. What is the current document? The web page that you are displaying.
- Parentheses - The words "document.writeln" must be followed by a set of parentheses.
- "We hope you enjoy this" - Here you can have any message you like. You can change this text for anything else as long as you enclose it in double quotes. You may include html tags. If you need to display a double quote, you should write \". For example: "And then the rabbit asked: \"What's up, Doc?\"".
- Semicolon at the end - always use a semicolon at the end of the statement.
The link below shows this example. Again, see the source of this page. You may copy this source and use it to make your own page.
Observe that the javascript can be included anywhere inside the HTML code (between the <body> and </body>). If you insert this code before the line "Welcome to Javascript" then the program would be executed first and your screen would look like this:
- We hope you enjoy this
- Welcome to Javascript
Once you have your program in an HTML file, you can either load it in a browser or simply click on it.
Exercise 1: Get yourself ready for javascript
Try the following steps:
- Start a simple text editing program. The simpler the better. In a PC you may try to use Notepad.
- Copy the code from the page2.htm example above and paste it to the document you are editing.
- Save the document. Make sure that you use the extension .htm or .html otherwise the browser will not work For example, name your program java1.htm.
- Now start your browser program (Internet Explorer or Netscape)
- On the top menu choose file -> open and select the file that you just created (java1.htm).
- Click OK and see the results.
Note: If you don't see the sentence "We hope you like it", then your browser has disabled the javascript. Look in the Tools -> internet options ->advanced (on Explorer) or Edit -> preferences -> advanced in Netscape and enable the javascript.
Most likely, in any computer application, one needs to store values, names, codes, etc. You may need to know a name or address, a phone number, a price or something like. Programming languages lets you use "variables" for that purpose. A variable is just a place in the computer memory where you can store a value but... the thing is, you want to make sure that you know where to find the things you put away, right? For this reason, all programming languages let you give a name of your choice that will remind you of what are the contents of that variable.
For example you could use names such as:
- customer_name to store the name of a client
- account to store the account number
- balance to store the balance on the account
- midterm_grade to store the grade on the midterm exam
Even though you may choose the name, there are some rules:
- Names must start with a letter or underscore;
- Names may contain letters, numbers and underscores only;
- Names may not contain blank spaces or other special characters;
- Names may contain upper or lower case characters, but they are different;
- There may be a list of names that are reserved and cannot be used (Keywords)
Some implementations of Javascript actually do not require you to declare the variables, but it is a good practice to do so. In the beginning of your program type the word "var" and then list the names that you will be using for variables.
For example: var name,points;
or
- var
- name,
- points;
The two alternatives on the left are entirely equivalent. A statement in Javascript may start in one line and end in another. The end of the statement is denoted by the semicolon. The second option lists each variable in a separate line and may make the program more readable.
That is it. This will tell the computer that you will be using variables with names "name" and "points". You can write all the variables in the same line (separating them by commas) or you can write a variable in each line, still separating them by comma. In any case you should have a semicolon at the end.
For advanced users:
Javascript does not require the programmer to specify a type. In fact, the variables do not have a type and can hold any type of data.
The next example uses the variables "name" and "points".
This is the contents of this file:
- // declare variables
- var
- name,
- points;
- // store values in the variables
- name="Alfred";
- points=25;
- document.writeln(name);
- document.write(" has ");
- document.write(points);
- document.write(" points");
As you can see, after the declaration, we set name equal to "Alfred" and points equal to 25. The next set of lines simply write the information to the web page.
Notice the following:
When you want to refer to a string of characters (like "Albert"), you have to enclose it in double quotes. If you don't enclose in quotes, the computer will think that there is a variable "Albert" which may contain a different value.
The equal sign works in most programming language to assign a value to a variable. It is important to notice that the variable on the left side of the equal sign receives the value. It is legal to write points=25, but it is not legal to write 25=points, because that would mean you want to move the value in "points" to 25, but 25 cannot be changed!
This program writes points and "points". Without the double quotes, the computer will find the value stored in the variable points, which is 25, and will print that value. With the double quotes, the computer will not try to look for a variable. It will simply print whatever is inside the quotes.
Variables can be manipulated. Variables containing numeric values can be added subtracted, multiplied or divided by some other variable containing a numeric value. Here are the operators:
- + addition
- - subtraction
- * multiplication
- / division
Here are some examples of things you could do with the variables:
- points=points*1.20; // this would increase the value in points by 20%
- points=points+5; // this would increase the value in points by 5
Here are some examples of things you could do with variables that contain text:
name="Dr. "+name+" ,PhD";
Variables containing text can be added in a different manner. The addition simply appends more text to the variable. In the above example, we are adding "Dr. " (notice a blank space after the dot) with the name and then adding " ,PhD". If you display the value in "name", you should see:
Dr. Albert, PhD
There are limited things you can do simply assigning values in your program. Often you will need to ask the user to input some information. The next step is to ask the user to type his or her name and to input the number of points.
This will require us to use another object in Javascript: the windows object.
The windows object is a new window that you can create to either send a message to the user or to request some value as input.
To send a message:
window.alert("Your message goes here");
To request an input:
name=window.prompt("Please enter your name"," ");
Can you modify the page3.htm program to request your name and number of points and display that?
Please try.
The windows prompt has two parameters inside the parentheses. The first sentence, enclosed in double quotes, is what you want to display in the window. Usually, this should tell the user what kind of information you want. The second sentence is a value that will be typed as a suggestion in the box. The user can either leave that value or type over it.
Important:
If you are using a prompt to read a numerical value, you may need to "massage" it before you can use it. Javascript tends to think that you are entering characters. For example, take:
- x=window.prompt("enter a value");
- y=x+x;
- document.write(y);
If you enter "1", you will see a result "11" because Javascript treated your value as a character, not as a number.
To overcome this problem, you need to parse the value as an integer:
newx=parseInt(x);
Notice that all characters in "parseInt" except for the "I" are lowercase!
Exercise 2:
Write a program that asks the user to input a name and two values. The values could be scores in two exams. Your program should then compute the average score and display it.
Notice that you will need variables to hold: the name, the first score, the second score, the average score.
Displaying images
You can use HTML to display an image or picture in the current web page. If you have an image whose name is 1.jpg which happens to be in the same directory as the current page, it would suffice to include the following html code:
<img src="1.jpg"> // display image 1.jpg
Of course, instead of "1.jpg" you could write the name of any image file that you wanted to load. If the image file was to be found in a different folder, then you would have to specify the folder in addition to the image file name.
If you want to experiment with images, you can download the pictures below to your folder. After clicking on the hyperlink, a blank page will show with the image file. To save a copy of the image file to your folder, just click with the RIGHT button on the image and select "save image as..." to save a copy of it.
Once you know the proper html code to display an image, you can have an image displayed either by including the html code (as above) right in the html part of your page or by using document.display("<img src=\"1.jpg\">");
Note: displaying double quotes
Double quotes (") are used in Javascript to delimit a sequence of characters that are supposed to be displayed exactly as written. However, if the characters we want to display include a double quote, the computer would be confused thinking that the end of the character string was reached. To avoid that problem, whenever we need to display double quotes, we precede the double quotes with a backslash. This is why we had document.display("<img src=\"1.jpg\">") instead of document.display("<img src="1.jpg">") in the above example.
displaying images dynamically
As long as you want to display always the same image (or text) in your page, you can use plain HTML and will have no real need for writing a program. The real usefulness of programming is to make it possible to generate a different web page depending on the situation.
Consider the following example:
You have six images (numbered 1 through 6). Instead of displaying always the same image, you want to ask the user for the picture to be displayed. The user would then type a value (between 1 and 6) and you use this value to load the corresponding picture.
How would you do that?
you need to ask the user
Decisions in the program
Another major issue in programming is to tell the computer that you may want to do something different depending on some available information. This process is called decision.
Examples of decisions in programs:
- If the customer has available balance, then you cash the check; if not let the customer know.
- If the sale is performed in California, then add the sales tax.
- If the order is more than $100, then do not charge for shipping.
In all of the above examples you can see there is a condition and then one or two possible actions:
- Condition: account balance > 0
- Action (if true): cash the check
- Action (if false): let the customer know there is no cash
- another example:
- Condition: state is "California"
- Action (if true): add 8% sales tax to the cost
- Action (if false): none
Generally speaking the condition is a comparison between two values, or it could also be a combination of comparisons. This is important to remember because many beginner programmers have trouble in trying to express the condition. In order to compare two values, you should use one of the operators:
- < less than
- > greater than
- <= less than or equal to
- >= greater than or equal to
- == equals (notice there are two "=")
- != not equal
Notice that there are no operators => or =< Also, you need two equal signs to see if two values are equal
The above operators, that are used in comparisons, are called "relational" operators. Remember they try to express the relationship between two values.
So, how do you write a decision in Javascript?
This is the general format of a decision statement:
- if ( condition )
- {
- action if condition is true
- }
- else
- {
- action if condition is false
- }
The format shown on the left uses black characters to indicate that this is actually what you will write in the program. The text in green letters should be changed to whatever makes sense in your program.
For example, suppose we charge $10 for shipping and handling. However, if the order is over $100, shipping is free. How would we write that?
- if( totalorder>=100)
- {
- shipping=0;
- }
- else
- {
- shipping=10;
- }
Notice that you will either make shipping =0 or shipping =10, but you will never do both things! Only one of the alternatives is executed.
There are situations where you don't need the "else" part. In other words, You simply want to do something if the condition is true, but you want to do nothing special otherwise. For example, if today is the customer's birthdate, you may want to wish "happy birthday" (however, there is nothing special to say in other days).
In this case, you can totally omit the else clause of the statement which will look like this:
- if(customerbirthday == todaydate)
- {
- document.writeln("Happy birthday!");
- }
Exercise 3:
Use the same program as in exercise two to ask for two scores and compute the average. After computing the average, you should decide if the student passed the class or not. A student passes if the average is greater or equal to 50. You should display a message indicating if the student passed or failed the class.
Functions
You can create a smaller piece of program and teach it to the computer so that, next time you need to do the same thing, the computer will remember how to do it. If we compare a program with a recipe to cook "Eggs Benedict" , you may compare a function with a recipe to prepare "Hollandaise Sauce".
Thus, the recipe for Eggs Benedict could be:
Notice that the recipe could look much more difficult if the Hollandaise sauce was explained right there. Instead, the sauce preparation is moved to another chapter in the recipe book.
Similarly, a function is just like a small program. The function does not know any of the variables you have in your program, except for those you explicitly pass to the function as a parameter. For example, if you wanted to have a function that shows picture 1.jpg or 2.jpg or 3.jpg, etc.. you could have a function like this:
- document.writeln("<img src=\""+value+".jpg\" /img /p>");
All this function does is to take the number in variable "value" and generate an HTML code that loads the image that has the corresponding name. If value is 1, figure 1.jpg will be displayed, if value is 5, figure 5.jpg will be displayed. The convenience is that, in your program, you don't have to write the HTML code. All you have to do in order to display figure 3.jpg is:
show(3);
or, if the number of the picture that you want is contained in a variable "picturenumber", this is what you do:
show(picturenumber);
What will happen is that, at this point, the function "show" will be called and the number inside the parenthesis (picturenumber) will be copied to the variable "value" inside the function.