JavaScript Tutorial 5
Beginning Scripting and Objects


By now, you know quite a lot about JavaScript. You know about the origins of JavaScript, the basics of stealing JavaScript for you own use, and about events.

With this knowledge, you are ready to actually start creating your own custom scripts. This is an exciting time for you - and me - because you are about to cross the line from being a person who wants to learn JavaScript to being a person who KNOWS JavaScript.

The next thing that you need to learn involves the syntax (the grammar) of JavaScript, and how to use the built in power of the JavaScript language. Let's start with a very simple script. What we are going to do is use JavaScript to write a portion of an HTML page. The first example is a static (non-changing) script that always does the same thing. It doesn't involve any events - it runs automatically when the page is loaded - and only uses one built in method (document.write).

Clear everything out of your edit-text area, and make a new blank HTML document with a white background. It should look like this:

Type the following into CodeRunner below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

</body>
</html>


You should have gotten a blank white page.

What we want to do is use JavaScript to write some stuff into that page. This requires us to do several things that are always required when writing a script. Inside the body of your HTML document, add this script.

Type the following into CodeRunner below:
<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>


Your document should now look like this:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>

</body>
</html>


There's a lot of new stuff there that you probably don't know anything about. So, let's go through it.

The first thing you probably don't recognize is that <script> tag that contains the script. It is in red below if you can't find it:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>

</body>
</html>


The <script> tag is used to tell the browser that you want to use a script in your document. The language=javascript part tells the browser that your script is written in JavaScript - so that the browser uses the right interpreter when running your script.

The next thing that you probably don't recognize is the <!-- and //--> comment tags. They are in blue below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>

</body>
</html>


These comment tags (the same syntax as an HTML comment) hide the script from older browsers that don't support JavaScript. If you didn't put all of your JavaScripts in-between these comment tags, and someone with an older browser that doesn't support JavaScript opened your page, your script would be printed on the page with the rest of the HTML document. Since we do place our scripts into these comments tags, those older browsers just ignore the script.

That's it. Every time that you write a script, you must include these two things (the script tag and comments).

Now that we have that covered, let's move on to the fun stuff - the stuff that comes in between the script and comment tags - your script.

Do you see the different colored line below?
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>

</body>
</html>


This stuff is the part of the script that provides the functionality.

Notice that some of the things are separated by periods. This is how the script recognizes relationships between objects. You see, in object-oriented programming, you work on objects. In order to work on those objects, you have to define exactly which object you are working on. "How exactly do you do this?" you ask. Well, you have to use hierarchical relationships. Look at the diagram below:





car.gastank


Everybody know that a gas tank is part of a car (maybe we realize this more now that gas costs $1.50 a gallon). If you look at a car hierarchically, a gas tank is a sub-object of car, or in programming terms "inherits" from the car. If we were to refer to the gas tank in JavaScript, we would say car.gastank . By doing this, we would tell the browser to first look at the car so that it could then narrow it's search for the gas tank to only within that car (The car's engine would be car.engine). Simple huh?

Now, let's apply that knowledge to the script that we are analyzing right now. The first part of that different colored line above says window. This part tells that whatever comes next in the command line is found within the window. (It should be noted that every object in JavaScript begins its inheritance with window) The part that says document is that actual HTML document (which is an object) that you are creating. So, so far we have told the browser to look within the "window" object to find the document" object.

Did you notice that write in purple, right after the document object referral? If not, look again below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Here is some text");
//-->
</script>

</body>
</html>


We have finished telling the browser which object we want to work on, and are ready to tell it what we want to do to that object. You see, not only do objects inherit from other objects, but methods (JavaScript elements that actually perform some action) also inherit from objects.

HINT:
objects are nouns, Like car and gastank OR window and document.

methods are verbs. Like fill or write.


Lets see some examples of methods:

Let's say that our car is out of gas, and we need to fill it up. Look at this diagram:



car.gastank.fill(gas)


In this diagram, I want you to see that filling up the gas tank would be a method of gastank. It would NOT make any sense to fill the car with gas - that would be really hard and dangerous to clean. What you actually do is take your car to the gas station, walk around to the Gas Tank fill spout, and fill up your tank with gas. gas is a variable for fill. We could fill the tank with water if we wanted.

If we looked at this process in terms of JavaScript, we would say car.gastank.fill(gas).

fill() is a method of gastank. Because of this, car.fill(gas) would NOT work because fill() is NOT a method of car.

So, what we are doing when the script "fills" the tank, is calling the "fill()" method. Calling is a term which means "asking" or "instructing".

We use the same concept in the script that we are writing. What we want to do is write something into the document. So, naturally what we would type is window.document.write(). First we tell the browser what to work on, and then we tell it what to do. You haven't been exposed to many of the methods available to you yet, so just take my word that write() is a method of document.

write() is NOT a method of window. Let' try it and see what happens.



Type the following bogus into CodeRunner below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.write("Here is some text");
//-->
</script>

</body>
</html>
CLICK ON PREVIEW

It didn't work You got a message that said "write is not a function", which is another way of saying "write is not a method of window".

Okay hurry, and put that document back in.

Inside the parentheses after write there is some black text inside QUOTES. It reads write("Here is some text"). This text is telling the write method what to write . Hence, when the script runs, it writes whatever you have inside the parentheses onto the page. (In this case I used quotation marks around the string. {string is a fancy word for "a bunch of letters in a row " }.

I did this because I wanted to define the string from within the method caller. If I hadn't, the method would have attempted to write the value of some variable. Variables - items within the parentheses of a method - are treated as string values if placed between quotation marks, and as variable names or numbers if not placed between quotes. Later on in this tutorial, we'll go more in depth on the subject of variables.)

The last thing we need to learn about is that dark red semicolon (;) at the end of the line. The semicolon is used to tell the browser that that particular command is over. The semicolon must be used at the end of each command. If you don't use it, you will get syntax errors when you attempt to run the script. Try it. Try removing the semicolon and see what happens

(OK. Well technically you have to have that semicolon in there. But, some browsers aren't real picky, so you may not have gotten an error. Even if you didn't get the error, you should still always put that semicolon after every command - it's proper programming.)

If you haven't already, click 'Preview' to see what your first script does.

Neat Huh?

Congratulations, you have just written your first, very own JavaScript. You've learned the hard, abstract stuff. From here on out, JavaScript gets easier.

Beginning Scripting: Part 2

Let's make it interactive! In our next example, let's get input from the user first, and then write that value to the document.

Change your document to look like this. Don't worry if you don't understand the syntax yet, I'll explain later:
Type the following into CodeRunner below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write(window.prompt("Enter your name:",""));
//-->
</script>

</body>
</html>


Click 'Preview' to run your script.

It should have asked you for your name, and then written your name to the page. What it did is, when the write() method was looking for a value to write to the page, it called the window method "prompt( )" which returned the value that you type in. Make sense?

Then you say, "What if I want to type a whole sentence which includes the name of the user?" Easy. Change your document to look like this:

Type the following into CodeRunner below:
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
window.document.write("Your name is " + window.prompt("Enter your name:","") + ". Welcome to my page.");
//-->
</script>

</body>
</html>


Click 'Preview' to run your script.

It should have asked you for your name, and then written your name into a sentence on the page. This example uses a couple of semi-new things. The sentence portions within the quotes are treated as constant value - that is the script uses them as-is. Also, the '+' operator (operators will be discussed in depth in a later tutorial) is used to combine all of these things into one string.


Variables and More Objects



You might have noticed in the last example that the command line got kind of confusing. Methods within methods, strings being added to one another within a method, etc, can get a little messy. You can always do these things in one step like we did just now. But, as you do more and more programming, you will realize that it is well worth it to break your scripts down into small actions which contribute to the whole as much as possible. Not only does this make for easier initial programming, but it also makes it lots easier to find mistakes when your browser gives you an error message.

One of the major tools at your disposal for simplifying your scripts are variables.

Let's revisit our car example. Recall that when we wanted to fill the gastank with gas on our car we used the javascript equivalent:

car.gastank.fill(gas)


What kind of gas are we going to put in the gastank?

regular or premium or diesel or a mixture of all three (bear with me)?


For each decision we would make we would write:


car.gastank.fill(regular)
car.gastank.fill(premium)
car.gastank.fill(diesel)

How would we fill it with a mixture of all three? (once we decide then the method fill means to fill it up and so we are stuck with the choice of regular,premium, or diesel. Pretend we can't stop since this is javascript land we are in)

If we had a gas_can that we could put the different gases in first maybe.


a variable


Lets add the concept of variable to our picture. In this context a variable is like the gascan that we'll use to fill the car with. It is called a variable since what we put in it can vary (i.e. either regular,premium, or d iesel).



Let's see what the javascript equivalent of using the variable gascan would be:

Here is the picture:



and here is the javascript for filling up with regular:

gascan=regular;
car.gastank.fill(gascan);


And here it is for all three:

gascan=regular +premium + diesel;
car.gastank.fill(gascan);


What have we done? We've simply set gascan equal to regular +premium + diesel so that the variable gascan now CONTAINS the values regular and premium and diesel.

"regular", "diesel", and "premium" are values that the variable "gas" represents. Values are any constant entity. The number '1' is a value and the string "My House" is a value. Any variable can be set equal to these values.


The big lesson here is:
variables are containers for values




Now let's apply these concepts to our previous JavaScript example:

Click here to recall the example


Let's use variables in the last example to simplify it.

Change the script in your document below to look like this:
Click here to maximize
<html>
<head>
<title>
(Your title) </title>
</head>
<body bgcolor=white>

<script language=javascript>
<!--
beginPhrase = "Your name is ";
userName = window.prompt("Enter your name:","");
endPhrase = " Welcome to my page.";
finalString = beginPhrase + userName + endPhrase;
window.document.write(finalString);
//-->
</script>

</body>
</html>


Isn't that much better? Everything is spread out and easy to read. Let's analyze what we did.

All of the words in green are variable names. The browser worries about what to do with these variables, all you have to do is provide a name for them. Each of the first three variables hold the value of the dark red words. In the case of the userName variable, the window.prompt() method is first called, and the value that is entered by the user is stored in the userName variable.

The fourth variable - finalString - holds the combined value of each of the previous variables. In the "window.document.write()" line, the value of the finalString variable is written to the document. Click 'Preview'. You should get the same result as you did before.

Did you notice that when the finalString variable was called by the write() method, it was not enclosed by Quotes? This is because we did not wish final string to be treated as a constant value. Try enclosing finalString in quotes within the write() method and see what happens. It should write, "Your name is finalString. Welcome to my page." It did this because it thought you wanted to print the literal phrase "finalString" and not the value of the variable finalString because you enclosed the variable name in quotation marks.

One last note about variables before we move on to the next tutorial. You can use any word for a variable name as long as it is not either a reserved word by JavaScript or the name of a JavaScript object, method, or property. If you ever get an error regarding a variable that you don't think should be a problem, try changing to name of the variable to something a else that isn't one of the reserved words.

We haven't talked about this yet, but object names that you define work much the same way. You can't name an object with one of those reserved words either. I'll explain this more in detail in the next tutorial.

Save your work by clicking on SAVE TO WEB


Okay Save your page now!