Hour 14
JavaScript

Most of the techniques related to Python and Java that you’ve already learned can be applied in other programming languages. You might wonder why you should learn another language. Isn’t one enough? Different languages have different strengths, so in different situations, it makes sense to pick the language that will best enable you to perform the specific task you are looking to accomplish. For example, JavaScript is a programming language that enables you to improve websites by letting you customize the look and feel of your site’s presentation, increasing interaction with your website users, and validating any data they enter. You may think JavaScript is specifically for web masters and site designers, but it’s a simple language, and learning its basics can help you reinforce basic programming concepts.

Another advantage to JavaScript is that most programming languages need you to install an interpreter or compiler on your computer in order to execute your code, as you saw with Python. With JavaScript (and HTML), you only need a text editor. You type in your code, save it with an .html extension (or you can use .htm), and then open the saved file with your web browser.

Despite its name, JavaScript is not tied to the Java programming language (which is covered in Part III, “Java and Object-Oriented Programming,” of this book). In fact, the name has caused some confusion as computer fans thought that JavaScript was either an extension to or spin-off of Java, but it got the name because Java was a hot new language at the time, and some thought the connection of the scripting language to the web development language would benefit the adoption and growth of JavaScript. Misleading name aside, the more you learn JavaScript, the more you can make any websites you create stand out.

The highlights of this hour include the following:

Image Entering a first JavaScript program

Image Input and output with JavaScript, including mouse events

Image Variables in JavaScript

Image Recursion and conditionals in JavaScript

Getting Started with JavaScript

You can write JavaScript code in either a text editor or a word processor. If you choose the latter, you must make sure to save your files as text only. Save a program with an .html extension and then when you double-click on the file, it should automatically open with your default web browser.

Note

This lesson provides a quick overview of JavaScript, but the main points of it—comments, input, output, variables, operators, conditionals, and recursion—are similar to what you’ve already learned about Python and Java, just with minor syntactical differences. As mentioned earlier, the programming concepts covered in earlier hours will give you a leg up on learning other languages.

Using Comments in JavaScript

Just as you learned in earlier hours, when you studied Python and Java, the best programs have comments to make clear what is going on. JavaScript has both single-line and multi-line comments. As in Java, in JavaScript comments either start with a slash and asterisk (/*) or two consecutive slashes (//). The double-slash comment is known as a single-line comment. JavaScript ignores all text to the right of the two slashes. On the next line of code, JavaScript starts paying attention to the code again. When JavaScript encounters a comment that begins with the slash and asterisk, it treats everything that follows as a comment until it sees a closing asterisk and slash (*/). This type of comment can appear on a single line:

/* Next, the code calculates the area of the circle. */

Or it can go on for several lines:

/* This section is used to enter a contact
The user can enter a name, physical address,
up to 5 email addresses, home, work, and cell
phone numbers, and any additional comments
to help remember how they know the person. */

Entering Your First JavaScript Program

It’s time to jump in and write a JavaScript program. The program will be simple—particularly compared to the programs you’ve already written in Python. The goal here is to get you used to using to seeing how JavaScript and HTML work hand-in-hand.

Printing to the Screen with JavaScript

JavaScript has several ways to output to the screen. One of the easiest ways to print words on a website is to enclose them in quotation marks after a document.write statement. The following four statements embedded in an HTML document print names on the screen:

<script>
document.write("Sally Brown<br>");
document.write("John Wilson");
</script>

These statements produce the following output:

Sally Brown
John Wilson

Note

In JavaScript, using document.write is not always the best way to output text to a page. In fact, it has several limitations. But right now, you’re learning good generalized programming techniques, and it’s more about simple output than optimized output.

With any JavaScript statements, you need to bracket them with the <script> and </script> tags. You may also be wondering about the <br> tag at the end of the Sally Brown name. This signals to the browser to jump down to the next line and insert a line break. Without it, your output would look like this:

Sally BrownJohn Wilson

The quotation marks are not printed; they mark the string to be printed. But what if you want to print quotation marks? JavaScript has an easy solution. If you enclose your string to be printed in single quote marks, you can then include the double quotation marks as something to print. For example, if you added the line:

document.write('"what if I wanted to print quotation marks?"');

the output would be:

"what if I wanted to print quotation marks?"

Variables in JavaScript

Much like programs in Python (and all other programming languages), JavaScript programs store data in variables. The data might be a number, character, or string of characters.

Your programs can have as many variables as you need. As with Python, you should use descriptive names for your JavaScript variables when possible. However, you shouldn’t give a variable the same name as a JavaScript command or function, or you will create an error. Variables can hold numbers or character strings. You can use the optional command var to define a variable and the assignment operator (=) to assign a value to the newly created variable. Here are two sample variable statements:

sales = 956.34

var rate = .28

Tip

The var keyword is optional and requires more typing. However, many other programming languages require that you use a keyword to first declare a variable, so it’s good programming practice to use the optional var keyword.

Instead of using document.write, you can use the alert method to print values stored in variables. Just as in Python, you can print the variable names without quotes around them. If you have a variable with the area of a circle in it, the following two statements print the area and half area:

alert("The area of a circle with a radius of 3 is " + area);

alert("The area of a half circle is " + area/2);

Getting Keyboard Data with prompt

To make your JavaScript programs more valuable and your websites more interesting, you need to get information from users.

The prompt method is the opposite of alert. The prompt method receives values from the keyboard. You can then assign the values typed by the user to variables. When a program reaches a prompt call, it creates a dialog box that stays until the user types a value and clicks the OK button. Here is a prompt:

prompt("What is your favorite color?");

When program execution reaches this statement, the computer displays a dialog box with the message typed in the quotation marks. The dialog box is a signal to the user that something is being asked, and a response is desired. The clearer you make the statement you send to prompt, the easier it will be for the user to enter the correct information. If you created a program with the following prompt statement, it would produce the dialog box shown in Figure 14.3:

var radius = prompt("What is the radius of the circle? ");
images

FIGURE 14.3
The program does not advance until the user enters a value and then presses Enter or clicks OK.

When the user enters a value for the radius and clicks OK, the program proceeds.

Inputting Strings

Unlike in many other programming languages, a variable in JavaScript can hold either a number or a string. A user can enter any type of variable, numeric or string, through a prompt dialog box. For example, this line waits for the user to enter a string value:

var fname = prompt("What is your first name");

When the user types the name in response to the question, the name is put into the fname variable.

Caution

If the user only presses OK without entering a value in response to the prompt, JavaScript puts a value called null into the variable. A null value is a zero for numeric variables or an empty string for string variables. An empty string—a string variable with nothing in it—is literally zero characters long.

Capturing Mouse Events

JavaScript does not just interact with the keyboard entries from users. In addition, it can understand when the user either clicks the mouse on a specific button or passes into a particular region. These types of actions are called events; an event can trigger an action if you have written code for something to happen when the event occurs. For example, if the user clicks the mouse over a button on a web page form, the button’s onClick event is triggered if you have written code for it.

A rollover effect can apply to buttons or text on a web page. If text contains a rollover, the text can change color or can change in another way when the user points to the text. Often, such rollover effects are used for menu selection. Figure 14.4 shows a web page with JavaScript-enabled text before the user moves the mouse pointer over one of the text items. Figure 14.5 shows how the Store text changes when the user moves the mouse pointer over the text. This rollover effect is possible because the JavaScript that contains code to handle the rollover comes to the user’s computer inside the HTML web page. The code must run on the user’s computer to respond immediately to the mouse movement.

images

FIGURE 14.4
A web page with JavaScript looks like any other web page until the user activates a JavaScript scriptlet.

images

FIGURE 14.5
When the mouse pointer moves over text with a rollover effect, the JavaScript code changes the text’s appearance.

Understanding Arrays

Just as words and sentences are collections of single letters, strings are collections of characters, including words, spaces, letters, and any other special characters you choose to type or add by using ASCII functions. When you assign a string to a variable, like this:

var hometown = "Salt Lake City, Utah"

JavaScript considers this an array of characters and lets you access either the whole name or individual elements of that name. If you call the alert method and send hometown to it:

alert(hometown);

as you can probably guess, your output is a dialog box displaying:

Salt Lake City, Utah

What is probably not obvious is what would happen if you called the alert method and sent hometown[3] to it, as in this example:

alert(hometown[3]);

If you did this, you would get a single letter in the dialog box:

t

You may have figured out that the number in brackets refers to a specific letter or character in the string. (Good job if you did!) But you might wonder why it doesn’t output the letter l? After all, it is the third character in the name of the city. Recall that many programming languages start their counting with 0 instead of 1. So the S is hometown[0], the a is hometown[1], and the t is hometown[3]. You might be wondering what character corresponds to hometown[4]. It is the space, and the L is hometown[5]. When figuring arrays, JavaScript counts every character, including spaces. In this hometown variable, spaces are the 4, 9, and 15 spots in the array, and the comma is the 14 spot. This may seem confusing, but understanding arrays is important for almost every programming language. (It is important for some more than others. C, for example, does not have a string data type, so to work with strings in C, you need to create an array of characters.) For now, just know that every single character in a string corresponds to a specific number and that if you’re counting characters, start with 0 and include all spaces, characters, letters, and numbers.

Comparing Data with if

JavaScript provides the ability for a program to make a choice and to perform one action or another, depending on a condition. A JavaScript decision statement has two possibilities. To decide which path to take in a JavaScript program, you must use the if statement. The following if statement prints only if the value stored in age is less than 21:

if (age < 21)
   document.write("You cannot order alcohol");

As you saw with Python, you can test a series of relational statements. Whereas Python uses the if...elif...elif...else statements, JavaScript uses if...else if...else if...else.

Note

JavaScript allows for multiple if...else if...else if...else layers, but there is another way to handle several possible conditions or values to a single variable: by using the switch statement, which is not available in Python.

Looping Statements

Looping statements are another important feature of any programming language. JavaScript supplies three statements that control loops: for, while, and do...while.

Using the for Statement

The for statement is broken into three parts enclosed in parentheses to the right of the for:

for (i = 1; i <= 10; i++)
{
      document.write(i+"<br>");
}

Generally, the first part sets up a counter variable, and the second tests the counter variable using a relational operator. In this for statement, the variable i is set to 1, and 1 is clearly less than 10. Because the statement is true, the block of code inside the braces prints below the for statement. In this case, there’s only a single line of code in the block, but it prints the current value of i, which is 1.

When the block finishes executing, the third part of the for statement, the increment operator, runs. The increment operator (++) adds 1 to the variable, increasing i from 1 to 2. Now the for statement returns to the second part of the parenthetical section and again tests the relational statement there. 2 is still less than 10, so once again the block of code executes, printing the current value of i, which is 2. When the block is complete, the third portion of the for loop kicks in again, incrementing i by 1 to 3, and testing and looping continue until i is not less than or equal to 10, at which point the loop terminates, and the program proceeds to the next section of code.

Note

You don’t have to increase your test variable by 1. You can use a different operator (+=) to increase the value by any number. The statement i += 2 increases the counter by 2, and if you changed i++ to i += 2 in the earlier example, you would print only the odd numbers.

Using the while and do...while Loops

The while loop supplies a way to control loops through a relational test. Such a relational test uses the same relational operators used with if statements. (Refer to Table 6.1 in Hour 6, “Controlling Your Programs,” for a complete list of relational operators.)

Let’s return to the teacher-grading Python program from Hour 6. Listing 14.3 shows the same program but with JavaScript’s take on a while loop. Notice that the while continues looping while a certain condition is true. The condition is the teacher’s answer in response to having more tests to enter.

LISTING 14.3 You can control the grade program with a while loop

<! DOCTYPE html>
<html>
<head>
             <title>Grading Papers</title>
</head>
<body>
             <script>

             // Filename gradingpapers.html
             // program loops until the teacher does
             // not have any additional students

             var names = new Array();
             var grades = new Array();
             var ans = 'Y';
             i = 0;
             total = 0;
             while (ans == 'Y')
             {
                   names[i] = prompt("Enter student name:");
                   grades[i] = prompt("What was their test grade?");
                   total += parseFloat(grades[i]);
                   ans = prompt("Do you have another grade? (Y/N)");
                   i++;
            }
             for (j = 0; j < i; j++)
             {
                   document.write(names[j]+" got a "+grades[j]+"!<br>");
             }
             average = total / j;
             document.write("<p>The class average was "+average);
             </script>
</body>
</html>

This program keeps looping until the teacher indicates that there are no more grades to enter. Notice that the while is followed by a relational test, the result of which (true or false) determines whether the loop repeats again or quits. So if the conditional statement is false the first time, the block of code does not run at all. This program guarantees that the code will run one time because the ans variable is set to 'Y' to trigger the first pass through the loop. This is where a do...while loop can be more efficient. The only difference between a while loop and a do...while loop is the placement of the test expression. In Listing 14.3, the condition is tested, and then the code runs. A do...while loop runs at least once before the condition is tested. The following snippet is the while from the previous program rewritten as a do...while loop:

do
{
           names[i] = prompt("Enter student name:");
           grades[i] = prompt("What was their test grade?");
           total += parseFloat(grades[i]);
           ans = prompt("Do you have another grade? (Y/N)");
           i++;
} while (ans == 'Y');

This code would make more sense for your grading program; you would not have to set ans equal to 'Y' before the loop, and you’d run the code at least one time, which should almost always happen (unless every single student was sick on a particular day. Senior skip day, anyone?).

One added bonus to this program is the addition of a total variable, which gets the value of all grades and then is divided by the number of students who took the test in order to get an average grade. The program calculates this extra piece of information to add some additional programming value.

Tip

When using a while or do...while loop, make sure that somewhere in the block of code, you are altering the variable you are testing in the relational statement. Otherwise, you might get caught in an infinite loop where the program never ends.

Summary

This hour covers a lot of ground in some ways, but in others it serves as a bit of a review of what you learned in earlier hours, but now with JavaScript’s spin on these programming basics. You saw that it’s easy to enter and test JavaScript programs—as long as you have a browser to do so. JavaScript also has specific methods to handle mouse events, and this hour covers two of them. The next hour examines some additional ways you can use JavaScript to improve a website.

Q&A

Q. What is the difference between an alert dialog box and a prompt dialog box?

A. An alert dialog shares information with the website visitor, while a prompt dialog asks the user to enter specific information.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. True or false: Java and JavaScript are related to each other.

2. What filename extension should you use when you create a JavaScript program?

3. True or false: There’s no problem writing your programs in your typical word-processing program.

4. Tweak the program in Listing 14.1 so the dialog box asks, “Who wrote this program?” and so the answer the user gets upon clicking the button is your name.

5. How do you print words in the output window?

6. True or false: You use the same code to jump down a line in both document.write and alert methods.

7. What do the onmouseover and onmouseout events do?

8. What is the difference between a while loop and a do...while loop?

Answers

1. False. JavaScript and Java only share a name; JavaScript is a scripting language that was developed at the same time Java was hot, and it was named as it was to take advantage of Java’s popularity.

2. If your code is going to stay in an HTML document, you can use .html or .htm, but when you create separate JavaScript files, use .js.

3. False. The default method of saving files in word processors adds formatting codes that generate errors when you try to run your program. You can use a word processor, but you must always remember to save your files as plain text.

4. Here is one possible solution:

<!DOCTYPE html>
<html>
<head>
<script>

/* This is the function that gets
called when the user clicks the
button on the main page */
function displayProgrammer()
{
document.write("Dean Miller did!");
}
</script>
</head>
<body>


<h1>My First Program</h1>
<p id="demo">Who wrote this program?</p>

<button type="button" onclick="displayProgrammer()">And the answer is...</button>

</body>
</html>

5. Use document.write to display words in an output window. If you want to create a dialog box with the displayed words, use the alert method.

6. False. For document.write, you use the <br> code, which would not work in an alert (as it would print <br> to the screen). If you want to jump down a line, use the escape character " ". (Don’t feel bad if you got this wrong; we haven’t covered it yet.)

7. The onmouseover event triggers some code when the user’s mouse pointer passes into a specific object (such as an image, a banner, or a block of text). The onmouseout event triggers some code when the user’s mouse pointer leaves that object.

8. A do...while loop executes at least once before the conditional is tested, whereas a while op might never execute if the conditional is false.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172