Lesson 35: Introduction to forLoops
Lesson 36: Introduction to whileLoops
Lesson 37: End-of-Chapter Review—A Browser-Detect Script
From Joe Burns: One of the first things I ever saw done with JavaScript involved entering numbers on a page and having that page perform a mathematical computation using those numbers. The actual example was to figure a 15% tip. I thought that was the greatest thing I had ever seen. In fact, I wrote a script that does the same thing in Lesson 31, later in this chapter.
The purpose of this chapter is to take you back to math class, teach you how to make ran-dom events occur, and teach you how to use math to create JavaScript loops. All these events are seldom standalone items. Math typically is used to create a greater event. Case in point: Generating random numbers is nice, but what good is it unless the numbers help you to win the lottery?
JavaScript Goodies
148
Hey! That’s a great idea for a script.
But you have to walk before you can run, so let’s start with the basics of JavaScript mathe-matics.
Lesson 30: Math Operators
This page will not only show you how to use numeric values to perform computation with JavaScript, but it will also test your basic math skills. There might be a test later. Its purpose is to introduce you to mathematical operators, something you’ll use often. If you have done any type of computer programming before, you should be experiencing déjà vu! If not, don’t panic. Using this script, I’ll give you an easy introduction:
<SCRIPT LANGUAGE=”javascript”>
var result = 10 * 2 + 1 / 3 - 7
alert (“the answer to 10 * 2 + 1 / 3 - 7 is “ +result + “.”)
var numsums = 10 + 2
alert(“10 + 2 is “ + numsums)
var x = 10
alert(“ten is “ + x)
var y = x * 2
alert(“10 * 2 = “ + y)
var z = “Hello “ + “Good Bye”
alert(z)
</SCRIPT>
The script’s effect appears in Figure 6.1.
To see the effect on your own computer, click Lesson Thirty Script’s Effect in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/
lesson30effect.html.
The Arithmetic Operators
I think it would be hard to get to this point in the book and not be able to figure this one out pretty quickly. But it’s not the makeup of the script that’s important. The purpose here is to show you the JavaScript binary operators.
That’s a fancy way to refer to the addition (+), subtraction (-), multiplication (*), and divi-sion (/) symbols.
Percent (%) is also a binary operator. Its technical name is a modulus operator. However, it doesn’t create percentages. You actually have to create the percentages by hand, dividing one number into the other. The percent sign only returns any number left over, a remainder, in a division equation.
For example, the code 10 % 2would return 0because 2 divides into 10 evenly. But 10 % 3 would return the number 1. That’s what’s left over.
Deconstructing the Super Math Script
Well, maybe it’s not super, but it makes its point.
Each two-line piece of code sets up a mathematical equation or number usage and then uses an alertmethod to display the answers. Here’s the quick rundown:
var result = 10 * 2 + 1 / 3 - 7
alert (“the answer to 10 * 2 + 1 / 3 - 7 is “ +result + “.”)
Figure 6.1
Alert box displaying math answers.
JavaScript Goodies
150
We tried to create an equation that would use all the traditional binary operators. This is what came out. The answer is 13.333333333.
When you look at the equation, it might seem that the JavaScript is doing the wrong calcu-lation. If you pull out a calculator and follow the format, you might come up with this:
10*2+1(that equals 21) / 3-7(that equals -4)
Right? Well, JavaScript doesn’t see it that way. Remember, we’re dealing with a computer here. That computer just bulls through left to right without stopping to see this as a divi-sion problem. If you simply read the equation straight through, you’ll get the answer the computer did:
10*2(equals 20) + 1/3(a third) -7 = 13.333333
So how do you get around the computer bulling through? Parentheses, my friend.
Remember that from high school algebra? In math, the stuff in the parentheses is evaluat-ed first. Same here. If I wantevaluat-ed to turn this into a division problem with an equation on either side of the slash, it would look like this:
var result = (10 * 2 + 1) / (3 - 7)
Be careful when you put together mathematical equations in your JavaScript. Make sure the computer is figuring out what you want it to figure out. Always check the math against a calculator before offering your work to the public.
var numsums = 10 + 2
alert(“10 + 2 is “ + numsums)
The script sets a numsumsvariable. Can you see that it’s equal to 12 (10+2)? The script trans-fers that variable to an alertbox and displays that 10 + 2 = the variable, or 12:
var x = 10
alert(“ten is “ + x)
Another variable, x, is set to equal 10. The alertbox then displays that value:
var y = x * 2
alert(“10 X 2 = “ + y)
Another variable, y, is set to equal the xvariable multiplied by 2. That should be 20, right?
It is. The answer is displayed in the alertmethod:
var z = “Hello “ + “Good Bye”
alert(z)
Finally, the variable zis created, showing you can connect text using the computation symbols. That variable is then displayed using the alertboxes. (That will become very important later.)
The nice thing about the binary operator (+) is that it fulfils two duties. If it is placed between two numbers, it adds them. On the other hand, if it is placed between two strings, it puts them together into a single string, a process known as concatenation.
In Terms of Numbers and Binary Operators
Never put quotation marks around numbers. If you do put quotation marks around a num-ber, it becomes a string. That’s bad. For example, if you run the equation “3”+4, you will get34because the quotation marks made the “3”a string and set the 4 to a string, “4”; the plus sign simply put the two items together rather than adding them. If you want 7to be the result, don’t use any quotation marks so the plus sign sees both the 3 and the 4 as numbers.
Your Assignment
Write a script in which a prompt is used to ask the user for a number between 2 and 10.
Then, have that number’s square display on the page.
You do know what a square is, right? The number times itself.
You can see a possible answer to this assignment on your own computer by clicking Lesson Thirty Assignment in your download packet, or see it online at http://www.
htmlgoodies.com/JSBook/assignment30.html.
Lesson 31: Mathematics and Forms
After Chapter 5, “Forms: A Great Way to Interact with Your Users,” you should be pretty familiar with entering data into form fields and then getting values to show up.
Let’s take a look at that tip script that impressed Joe so much. It’s basic, but it does the trick:
<SCRIPT LANGUAGE=”javascript”>
function figureItOut() {
var dinCost = document.meal.dinner.value var tipCost = dinCost * .15
var bigtipCost = dinCost * .25 document.meal.tip.value = tipCost document.meal.bigtip.value = bigtipCost
JavaScript Goodies
152
}
</SCRIPT>
<FORM NAME=”meal”>
How much was dinner? $<INPUT TYPE=”text” NAME=”dinner”><BR>
<INPUT TYPE=”button” VALUE = “OK, Hit Me!” onClick=”figureItOut()”><P>
You should tip: $<INPUT TYPE=”text” NAME=”tip”><BR>
A big tipper would leave 25% $<INPUT TYPE=”text” NAME=”bigtip”><BR>
</FORM>
This script accepts input from the user, manipulates the data, and then posts an answer.
Very clever. You can see the script’s effect in Figure 6.2.
Figure 6.2
How much should you tip?
To see the effect on your own computer, click Lesson Thirty-One Script’s Effect in your down-load packet, or see it online at http://www.htmlgoodies.com/JSBook/lesson31effect.
html.
Deconstructing the Script
We’ll start with the form elements this time around because they are probably still some-what fresh in your mind:
<FORM NAME=”meal”>
How much was dinner? $<INPUT TYPE=”text” NAME=”dinner”><BR>
<INPUT TYPE=”button” VALUE = “OK, Hit Me!” onClick=”figureItOut()”><P>
You should tip: $<INPUT TYPE=”text” NAME=”tip”><BR>
A big tipper would leave 25% $<INPUT TYPE=”text” NAME=”bigtip”><BR>
</FORM>
First, note the formal names. The entire form is called meal, and the first input text box is calleddinner. The button is set up to trigger a function called, smartly enough,
figureItOut().
The results of the normal 15% tip shows up in a text box called tip, and the larger 25% tip result displays in a text box called bigtip.
Okay, now you know the players, so let’s get to the plays of the script:
function figureItOut() {
var dinCost = document.meal.dinner.value var tipCost = dinCost * .15
var bigtipCost = dinCost * .25 document.meal.tip.value = tipCost document.meal.bigtip.value = bigtipCost }
</SCRIPT>
We could have written out the hierarchy statement for the text box that accepted the user’s data, but because it was going to be used at least twice, we decided to assign a variable to it.document.meal.dinner.valuewas assigned the variable dinCost.
Now that we have that variable, we can start to create some mathematical equations with it.
The variable tipCostwas assigned to the cost of dinner multiplied by the traditional 15%, or .15, tip. Remember that the %sign does not mean percentage—it means the remainder of a multiplication. That’s why we use the .15 and .25 rather than 15% and 25%.
The variable bigtipCostwas assigned to the cost of dinner and multiplied by the better tip amount 25%, or .25.
JavaScript Goodies
154
Now you need to get those values into the correct form items when you click the button.
This is done by these lines of code:
document.meal.tip.value = tipCost document.meal.bigtip.value = bigtipCost
Notice the hierarchy statement points at the two form elements set up to receive the data.
The values assigned to each box are the variable names that represent the equations set up a moment ago.
When you put the whole process together, the function figures the tip amounts, assigns variable names to them, and writes them to the form element.
Nothing to it.
Your Assignment
Until now, you have had it easy with the math. Now let’s try something a little harder. Can you create a two–text box form with a button in the middle that changes Celsius degrees to Fahrenheit degrees?
Here’s the equation:
Fahrenheit = (Celsius X 9/5)+32
In case you want to get clever, Fahrenheit to Celsius is done using this formula:
(Fahrenheit - 32) X 5/9
TIP
You’ll do best by taking each section of the equation and making it its own variable. You can then do the equation with text, and you’ll be sure the numbers within the parentheses are being fig-ured by themselves.
You can see a possible answer to this assignment on your own computer by clicking Lesson Thirty-One Assignment in your download packet, or see it online at http://www.
htmlgoodies.com/JSBook/assignment31.html.
Lesson 32: Creating Random Numbers with a Date
This example introduces you to random numbers. People love random numbers for some reason. Here’s our example:
<SCRIPT LANGUAGE=”JavaScript”>
function rand() {
var now=new Date()
var num=(now.getSeconds())%9 var numEnd=num+1
alert(numEnd) }
</SCRIPT>
<FORM>
<INPUT TYPE=”button” VALUE=”Random Number from 1 to 10” onClick=”rand()”>
</FORM>
You can see the script’s effect in Figure 6.3.
Figure 6.3
Generating a random number.
To see the effect on your own computer, click Lesson Thirty-Two Script’s Effect in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/
lesson32effect.html.
Notice this in the script: The number after the %is the ending number. The following example picks a random number between 1 and 10.
But wait! The number after the %is 9! And there’s that %sign we keep mentioning for some reason. Keep reading to find out why.
JavaScript Goodies
156
Deconstructing the Script
We’ll start with the function this time:
function rand() {
var now=new Date()
var num=(now.getSeconds())%9 var numEnd=num+1
alert(numEnd) }
It takes a few steps to get the random number.
First, you must set aside a function. We called ours rand().
Next, we set aside a variable that will act as a method called new Date().
Another variable, called num, is set aside. It contains the method getSeconds()to grab a number between 0 and 59.
JavaScript counts everything and starts counting from 0. The number returned from getSeconds()is divided by 9, and a remainder is returned. Remember that the %sign returns only the remainder of a division.
The remainder has one number added to it. That number is assigned the variable name numEnd.
Thealert()method then displays the number.
How Does That Give a Random Number?
Here’s the concept. 9 divides into 0 through 60 approximately 6.7 times. So, every six and a half seconds or so, a new number can be returned.
Let’s say the second returned is 54. 9 divides into 54 with a result of 6. That’s a perfect number. There is no remainder. Therefore, the remainder is 0. Remember that the %sign returns only the remainder of a division. 1 is added, and the random number is 1.
Here’s another example. The second return is 22. 9 divides into it 2.4 times. 4 is the remainder. 1 is added to it, and you get a random number of 5.
You’ll never get a 0 returned as the random number because 1 is always added to the mix.
It’s hard to believe it works, but it does.
The Form Items
<FORM>
<INPUT TYPE=”button” VALUE=”Random Number from 1 to 10” onClick=”rand()”>
</FORM>
There’s no real need to name the form or the form items in this case. None of the elements comes into play. The button is simply there to act as a trigger to produce the number through the rand()function.
It’s a neat trick.
Your Assignment
Do you play the lottery? Let’s create a JavaScript that picks the three-digit daily lotto draw-ing numbers. You have to return three random numbers, 0–9.
Make the numbers appear on an alert box. For good measure, put the text Good Luck!in the status bar.
TIP
If you use getSeconds()for all three number generators, you’ll always get all three numbers the same.
You can see a possible answer to this assignment on your own computer by clicking Lesson Thirty-Two Assignment in your download packet, or see it online at http://www.
htmlgoodies.com/JSBook/assignment32.html.
Lesson 33: Creating Random Numbers Through Mathematics
This script enables you to create a random number using JavaScript mathematics state-ments rather than relying on a date return:
<SCRIPT LANGUAGE=”javascript”>
var num = Math.round(35 * Math.random());
document.write(“Random number between 0 and 35: <B>” + num + “</B>.”)
</SCRIPT>
The script’s effect appears in Figure 6.4.
JavaScript Goodies
158
To see the effect on your own computer, click Lesson Thirty-Three Script’s Effect in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/
lesson33effect.html.
Deconstructing the Script
It might not seem at first that there is a lot to this script, but it is quite useful. First, it’s compact, and it always returns a positive integer starting at 0.
In addition, the fact that it runs without a function is also helpful.
Here’s the line of code that does the trick:
var num = Math.round(35 * Math.random());
The line is set up as a variable assigned the name num. That enables you to post the result anywhere on the page.
The mathematics are done through two object.methodstatements.
Mathis an object that alerts the browser that the methods which follow are to be used specifically to produce mathematical results. The Mathobject itself carries no value; it sim-ply sets the course of the methods that follow to do math.
Math.round()is an object.methodstatement that takes whatever is in its argument and rounds it to the nearest integer.
Figure 6.4
Generating a random number through math.
Math.random()is an object method that returns a number between 0 and 1. Now, that might sound silly at first, but here’s another thing about how JavaScript counts. It starts at 0 and goes up. Better than that, JavaScript has the capability to count in milliseconds.
There are actually 999 different responses this Math.randomcan return, from .001 up to .999.
The number 35 is in there because we put it there. It is known as the upper limit. The answer returns between 0 and 35 because it is mathematically impossible to go higher than what you’re multiplying.
For example, Math.random()returns .234. 35 times .234 is 8.19. That rounds down because it’s closer to 8 than it is to 9. Therefore, the random number produced is 8.
The line
document.write(“Random number between 0 and 35: <B>” + num + “</B>.”)
writes the random number to the document surrounded by text that explains to the user what the number represents.
But what if you do not want 0 as one of the random numbers? Well, you’ll have to do two things:
Add 1 to the output of the random number equation. Remember how we did that in the last lesson?
Make the upper limit 34. If you leave it at 35, there’s every chance that 35 will be the number returned and adding would make the number 36. That’s bad.
Isn’t this math stuff fun?
The Math Object
TheMathobject is amazing. Table 6.1 shows all the methods that can be attached to it.
When using the Mathobject, think of it in the same way as you would the
Date.getSomething()method. It functions in a similar fashion and returns numbers the same way.
Where you see argumentin the table, I mean a mathematical equation.
For example, the first Math.method()—Math.abs()—could be written this way:
Math.abs((22*3) / 4)
JavaScript Goodies
160
Table 6.1 Math Object Methods
Method Return Value
Math.abs(argument) The absolute value of an argument Math.acos(argument) The arc cosine of the argument Math.asin(argument) The arc sine of the argument Math.atan(argument) The arc tangent of the argument Math.atan2(argument1, argument2) The angle of polar coordinates x and y Math.ceil(argument) The number one larger than or equal to the
argument rounded up to the nearest integer Math.cos(argument) The cosine of the argument
Math.exp(argument) A natural logarithm
Math.floor(argument) The number 1 less than or equal to the argu-ment rounded down to the nearest integer
Math.E Base of natural logarithms, approximately
2.718
Math.LN2 Logarithm of 2 (appx: 0.6932), natural loga-rithm
Math.LN10 Logarithm of 10 (appx: 2.3026), natural loga-rithm
Math.log Base-10 logarithm
Math.LOG10E Base-10 logarithm of E
Math.LOG2E Base-2 logarithm of E
Math.max(arg1,arg2) The greater of the two arguments Math.min(arg1,arg2) The lesser of the two arguments
Math.PI The value of pi, approximately 3.14159
Math.pow(arg1, arg2) arg1raised to the arg2power
Math.random A random number between 0 and 1,
noninclusive of either 000 or 1 Math.round(value) Rounds to the nearest integer Math.sin(argument) The sine of the argument Math.sqrt(argument) The square root of the argument
Math.SQRT1_2 The square root of 1/2
Math.SQRT2 The square root of 2
Math.SQRT2 The square root of 2