Here's part of "The Secret Guide to Computers," copyright by Russ Walter, 29th edition. For newer info, read the 33rd edition at www.SecretFun.com.

JavaScript & JScript

Pages 319-327 explained how to create Web pages by using HTML. Unfortunately, HTML is not a complete programming language.

For example, HTML lacks commands to do arithmetic. In HTML, there is no command to make the computer do 2+2 and get 4.

HTML lacks commands to create repetitions (which are called loops). In HTML, there is no command to make the computer repeat a task 10 times.

In 1996, a Netscape employee, Brendan Eich, invented an HTML supplement called LiveScript, which lets you create Web pages that do arithmetic, loops, counting, and many other fancy tricks. When folks noticed that LiveScript looks like a stripped-down version of Java, Netscape changed the name “LiveScript” to JavaScript.

JavaScript is included as part of Netscape Navigator (if you have Navigator version 2 or later). JScript (Microsoft’s imitation of JavaScript) is included as part of Internet Explorer (if you have Internet Explorer version 3 or later).

Now every popular computer comes with JavaScript or JScript. That’s because Netscape Navigator is free, Internet Explorer is free, Netscape Navigator & Internet Explorer are both available for IBM and Macs, and Internet Explorer is part of Windows.

Netscape, Microsoft, and the European Computer Manufacturers Association (ECMA) all decided to make JavaScript and JScript resemble each other more, by creating a standard called ECMAScript.

This chapter explains how to use JScript to create powerful Web pages. (JavaScript and ECMAScript are similar.)

Before learning JScript, make sure you’ve learned HTML (by reading pages 319-327).

 

 

 

 

 

 

Simple program

You can create a Web page that says —

We love you

by typing this HTML program:

We <i>love</i> you

I explained how on page 319. (If you forget how, reread page 319 and practice it now.)

To create a Web page that makes the computer do 2+2 instead, type instead this HTML program (which includes a JScript program):

<script>

document.write(2+2)

</script>

The first line, which says <script>, warns the computer that you’re going to start typing a JScript (or JavaScript) program. The next line, which is written in JScript, means: on the Web-page document, write the answer to 2+2. The bottom line, which says </script>, marks the bottom of your JScript program. When you run that program, the computer will do 2+2 and write this answer:

4

In that example, the first line, <script>, is an HTML tag. Like all HTML tags, it’s enclosed in angle brackets: the symbols <>. That tag marks the beginning of your JScript program. The bottom line, </script>, is an HTML tag that marks the end of your JScript program. Between those two tags, write your JScript program.

 

Longer example

Let’s make the computer write “We love you”, then write the answer to 2+2, then write “ever and ever”. This program does it:

We <i>love</i> you

<script>

document.write(2+2)

</script>

ever <i>and ever</i>

The first line makes the computer write “We love you”. The next three lines hold the JScript program making the computer write the answer to 2+2, which is 4. The bottom line makes the computer write “ever and ever”. So altogether, the computer will write:

We love you 4 ever and ever

Fancier arithmetic

This program makes the computer write the answer to 8-3:

<script>

document.write(8-3)

</script>

The computer will write:

5

This program makes the computer write the answer to -26.3+1:

<script>

document.write(-26.3+1)

</script>

The computer will write:

-25.3

Multiplication

To multiply, use an asterisk. So to multiply 2 by 6, type this:

<script>

document.write(2*6)

</script>

The computer will write:

12

Division

To divide, use a slash. So to divide 8 by 4, type this:

<script>

document.write(8/4)

</script>

The computer will write:

2

Avoid commas

Do not put commas in big numbers. To write four million, do not write 4,000,000; instead, write 4000000.

E notation

If the computer’s answer is huge (at least 1000000000000000000000) or tiny (less than .000001), the computer will typically print an e in the answer. The e means “move the decimal point”.

For example, suppose the computer says the answer to a problem is:

1.5864321775908348e+21

The e means, “move the decimal point”. The plus sign means, “towards the right”. Altogether the e+21 means, “move the decimal point towards the right, 21 places.” So look at 1.5864321775908348, and move the decimal point towards the right, 21 places; you get 1586432177590834800000.

So when the computer says the answer is 1.5864321775908348, the computer really means the answer is 1586432177590834800000, approximately. The exact answer might be 1586432177590834800000.2 or 1586432177590834800000.79 or some similar number, but the computer prints just an approximation.

Suppose your computer says the answer to a problem is:

9.23e-7

After the e, the minus sign means, “towards the left”. So look at 9.23, and move the decimal point towards to left, 7 places. You get:

.000000923

You’ll see e notation rarely: the computer uses it just if the answer is huge or tiny. But when the computer does use e notation, remember to move the decimal point!

The highest number

The highest number the computer can handle well is about 1E308, which is 1 followed by 308 zeros. If you try to go much higher, the computer will give up and say the answer is:

Infinity

The tiniest decimal

The tiniest decimal the computer can handle accurately is 1E-309 (which is a decimal point followed by 309 digits, 308 of which are zeros). If you try to go tinier, the computer will either write 0 or give you a rough approximation.

Long decimals

If an answer is a decimal that contains many digits, the computer will typically write the first 16 significant digits accurately and the 17th digit approximately. The computer won’t bother writing later digits.

For example, suppose you ask the computer to write 100 divided by 3, like this:

<script>

document.write(100/3)

</script>

The computer will write:

33.333333333333336

Notice that the 17th digit, the 6, is wrong: it should be 3.


Division by 0

If you try to divide 1 by 0, the computer will say the answer is:

Infinity

If you try to divide 0 by 0, the computer will say the answer is —

NaN

which means “Not a Number”.

Order of operations

JScript (and JavaScript) handle order of operations the same as QBASIC, Visual BASIC, and most other computer languages.

For example, if you type this program —

<script>

document.write(2+3*4)

</script>

the computer will “start with 2 then add three 4’s”, so it will write this answer:

14

You can use parentheses the same way as in algebra. For example, if you type —

<script>

document.write(5-(1+1))

</script>

the computer will compute 5-2 and write:

3

 

Strings

You learned how to put a JScript (or JavaScript) program in the middle of an HTML program. You can also do the opposite, you can put HTML in the middle of a JScript program.

For example, this JScript program makes the computer write “We love you”:

<script>

document.write("We <i>love</i> you")

</script>

The computer will write:

We love you

In that program, the “We <i>love</i> you” is called a string of characters. Each string must begin and end with a quotation mark. Between the quotation marks, put any characters you want the computer to write. A string can include an HTML tag, such as <i>.


Strings with numbers

If you bought 750 apples and buy 12 more, how many apples do you have altogether? This program makes the computer write the answer:

<script>

document.write(750+12," apples")

</script>

The computer will write the answer to 750+12 (which is 762) then the word “ apples” (which includes a blank space), so altogether the computer will write:

762 apples

This program makes the computer put the answer into a complete sentence:

<script>

document.write("You have ",750+12," apples!")

</script>

The computer will write “You have ” then 762 then “apples!”, so altogether the computer will write:

You have 762 apples!

Writing several strings

Here’s another example of strings:

<script>

document.write("fat")

document.write("her")

</script>

The computer will write “fat” then “her”, so altogether the computer will write:

father

Let’s make the computer write this instead:

fat

her

To do that, make the computer press the ENTER key before her. Here’s how: say <br> (which is the HTML tag to break out a new line), like this —

<script>

document.write("fat")

document.write("<br>her")

</script>

or like this:

<script>

document.write("fat<br>her")

</script>

Addition

You can add strings together by using the + sign:

“fat”+“her” is the same as “father”

2+2+“ever” is the same as “4ever”


Variables

A letter can stand for a number. For example, x can stand for the number 47, as in this program:

<script>

x=47

document.write(x+2)

</script>

The second line says x stands for the number 47. In other words, x is a name for the number 47.

The next line says to write x+2. Since x is 47, the x+2 is 49; so the computer will write:

49

That’s the only number the computer will write; it won’t write 47.

A letter that stands for a number is called a numeric variable.

A letter can stand for a string. For example, y can stand for the string “We love you”, as in this program:

<script>

y="We <i>love</i> you"

document.write(y)

</script>

The computer will write:

We love you

A letter that stands for a string is called a string variable.

A variable’s name can be short (such as x) or long (such as town_population_in_1999). It can be as long as you wish! The name can contain letters, digits, and underscores, but not blank spaces. The name must begin with a letter or underscore, not a digit.

Increase

The symbol ++ means “increase”. For example, ++n means “increase n”.

This program increases n:

<script>

n=3

++n

document.write(n)

</script>

The n starts at 3 and increases to 4, so the computer prints 4.

Saying ++n gives the same answer as n=n+1, but the computer handles ++n faster.

The symbol ++ increases the number by 1, even if the number is a decimal. For example, if x is 17.4 and you say ++x, x will become 18.4.

Decrease

The opposite of ++ is --. The symbol -- means “decrease”. For example, --n means “decrease n”. Saying --n gives the same answer as n=n-1 but faster.

Arrays

A letter can stand for a list. For example, x can stand for a list, as in this program:

<script>

x=["love","death",48+9]

document.write(x)

document.write(x[2]/4)

</script>


That makes x be a list of three items: “love”, “death”, and the answer to 48+9 (which is 57). The next line makes the computer write all of x, like this:

love,death,57

In x (which is a list), there are three items:

The original item, which is called x[0], is “love”.

The next item, which is called x[1], is “death”.

The next item, which is called x[2], is 57.

The next line says to write x[2]/4, which is 57/4, which is 14.25; but since we didn’t say <br>, the computer writes the 14.25 on the same line as the list, so altogether you see:

love,death,5714.25

A list is called an array.

Delayed definition If you want x to be a list of three items but don’t want to list the three items yet, you can be vague by saying just —

x=Array(3)

Later, you can define x by lines such as:

x[0]="love"

x[1]="death"

x[2]=48+9

 

Pop-up boxes

Here’s how to make a box appear suddenly on your screen.

Alert box

To create a surprise, make the computer create an alert box:

<script>

alert("Warning: your hair looks messy today")

document.write("You won't become Miss America")

</script>

When a human runs that program, the screen suddenly shows an alert box, which contains this message: “Warning: your hair looks messy today”. (The computer automatically makes the box be in front of the Web page, be centered on the screen, and be wide enough to show the whole message.) The alert box also contains an OK button. The computer waits for the human to read that alert message and click “OK”.

When the human clicks “OK”, the alert box disappears and the computer obeys the program’s next line, which makes the computer write onto the Web page:

You won’t become Miss America

In an alert box, the computer uses its alert font, which you cannot change: you cannot switch to italics or bold; you cannot put HTML tags into that message.

Here’s another example:

<script>

alert("You just won a million dollars")

document.write("Oops, I lost it, better luck next time")

</script>

When a human runs that program, an alert box tells the human “You just won a million dollars”; but when the human clicks “OK”, the Web page says “Oops, I lost it, better luck next time”.


Prompt box

To ask the human a question, make the computer create a prompt box:

<script>

x=prompt("What is your name?","")

document.write("I adore anyone whose name is ",x)

</script>

When a human runs that program, the computer creates a prompt box, which is a window letting the human type info into the computer. (The computer automatically makes the box be in front of the Web page and be slightly above the screen’s center.) It contains this prompt: “What is your name?” It also contains a white box (into which the human can type a response) and an OK button.

The computer waits for the human to type a response. When the human finishes typing a response, the human must click the OK button (or press ENTER) to make the window go away.

Then the Web page reappears and the computer makes x be whatever the human typed. For example, if the human typed —

Maria

x is Maria, so the computer writes this onto the Web page:

I adore anyone whose name is Maria

In that program, notice that the prompt line includes these symbols before the last parenthesis:

                             ,""

If you type this instead —

                             ,"Type your name here"

here’s what happens: the white box (into which the human types a name) will temporarily say “Type your name here”, until the human starts typing.

College admissions This program makes the computer write a letter admitting you to the college of your choice:

<script>

college=prompt("What college would you like to enter?","")

document.write("You're admitted to ",college,". I hope you go to ",college,".")

</script>

<p>Respectfully yours,

<br>The Dean of Admissions

When you run the program, a prompt box appears, asking “What college would you like to enter?” Type your answer (then click OK or press ENTER).

For example, if you type —

Harvard

the college will be “Harvard”, so the computer will write “You’re admitted to” then “Harvard” then “. I hope you go to ” then “Harvard”, then “.” then the remaining HTML code, like this:

You’re admitted to Harvard. I hope you go to Harvard.

 

Respectfully yours,

The Dean of Admissions

If you type this instead —

Hell

the computer will write:

You’re admitted to Hell. I hope you go to Hell.

 

Respectfully yours,

The Dean of Admissions

All the writing is onto your screen’s Web page. Afterwards, if you want to copy that writing onto paper, click Internet Explorer’s Print button. (If you don’t see the Print button, make it appear by maximizing the Internet Explorer window.)

Numeric input This program makes the computer predict your future:

<script>

y=prompt("In what year were you born?","")

document.write("In the year 2020, you'll turn ",2020-y," years old")

</script>


When you run the program, the computer asks, “In what year were you born?” If you answer —

1962

y will be 1962, and the computer will write:

In the year 2020, you'll turn 58 years old.


Control statements

A program is a list of statements that you want the computer to perform. Here’s how to control which statements the computer performs, and when, and in what order.

If

This program makes the computer discuss the human’s age:

<script>

age=prompt("How old are you?","")

document.write("I hope you enjoy being ",age)

</script>

When that program is run, the computer asks “How old are you?” and waits for the human’s reply. For example, if the human says —

15

the age will be 15. Then the computer will print:

I hope you enjoy being 15

Let’s make that program fancier, so if the human is under 18 the computer will also say “You are still a minor”. To do that, just add a line saying:

if (age<18) document.write("<br>You are still a minor")

Notice you must put parentheses after the word “if”. Altogether, the program looks like this:

<script>

age=prompt("How old are you?","")

document.write("I hope you enjoy being ",age)

if (age<18) document.write("<br>You are still a minor")

</script>

For example, if the human runs the program and says —

15

the computer will print:

I hope you enjoy being 15

You are still a minor

If instead the human says —

25

the computer will print just:

I hope you enjoy being 25

Else

Let’s teach the computer how to respond to adults.

Here’s how to program the computer so that if the age is less than 18, the computer will say “You are still a minor”, but if the age is not less than 18 the computer will say “You are an adult” instead:

<script>

age=prompt("How old are you?","")

document.write("I hope you enjoy being ",age)

if (age<18) document.write("<br>You are still a minor")

else document.write("<br>You are an adult")

</script>

In programs, the word “else” means “otherwise”. The program says: if the age is less than 18, write “You are still a minor”; otherwise (if the age is not less than 18), write “you are an adult”. So the computer will write “You are still a minor” or else write “You are an adult”, depending on whether the age is less than 18.

Try running that program! If you say you’re 50 years old, the computer will reply by saying:

I hope you enjoy being 50

You are an adult

Fancy relations

Like JavaScript, Java’s “if” statement uses this notation:

Notation                                     Meaning

if (age<18)                 if age is less than 18

if (age<=18)              if age is less than or equal to 18

if (age==18)              if age is equal to 18

if (age!=18)              if age is not equal to 18

if (age<18 && weight>200)  if age<18 and weight>200

if (age<18 || weight>200) if age<18 or weight>200

if (sex=="male")          if sex is “male”

if (sex<"male")           if sex is a word (such as “female”)
                                that comes before “male” in  dictionary

if (sex>"male")           if sex is a word (such as “neuter”)
                                                        that comes after “male” in  dictionary

Notice that in the “if” statement, you should use double symbols: you should say “==” instead of “=”, say “&&” instead of “&”, and say “||” instead of “|”. If you accidentally say “=” instead of “==”, the computer will gripe. If you accidentally say “&” instead of “&&” or say “|” instead of “||”, the computer will still get the right answers but too slowly.

Braces

If a person’s age is less than 18, let’s make the computer write “You are still a minor” and make maturity=0. Here’s how:

if (age<18)

{

    document.write("You are still a minor")

    maturity=0

}

Here’s a fancier example:

if (age<18)

{

    document.write("You are still a minor")

    maturity=0

}

else

{

    document.write("You are an adult")

    maturity=1

}

For

Here’s how to write the numbers from 1 to 10:

<script>

for (i=1; i<=10; ++i) document.write(i," ")

</script>

That means: do repeatedly, for i starting at 1, while i is no more than 10, and increasing i after each time: write i followed by a blank space (to separate i from the next number). The computer will write:

1 2 3 4 5 6 7 8 9 10

If instead you want to write each number on a separate line, say “<br>” (which means “break for new line”) before each number:

<script>

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

</script>

The computer will write:

 

1

2

3

4

5

6

7

8

9

10


Let’s get fancier! For each number, let’s make the computer also write the number’s square (what you get when you multiply the number by itself), like this:

 

1 squared is 1

2 squared is 4

3 squared is 9

4 squared is 16

5 squared is 25

6 squared is 36

7 squared is 49

8 squared is 64

9 squared is 81

10 squared is 100

Here’s how:

<script>

for (i=1; i<=10; ++i) document.write("<br>",i," squared is ",i*i)

</script>

To get even fancier, let’s make the computer write that info in a pretty table, like this:

NAME

SCORE

1

1

2

4

3

9

4

16

5

25

6

36

7

49

8

64

9

81

10

100

As I explained on page 322, you do that by saying <table border=1> above the table, <tr> at the beginning of each table row, <th> at the beginning of each column heading, <td> at the beginning of each data item, and </table> below the table:

<table border=1>

<tr><th>NAME<th>SCORE

<script>

for (i=1; i<=10; ++i) document.write("<tr><td>",i,"<td>",i*i)

</script>

</table>

Onclick

Let’s create a Web page that asks, “What sex are you?” Below that question, let’s put two buttons labeled “Male” and “Female”. If the human clicks the “Male” button, let’s make the computer say “So is Frankenstein”. If the human clicks the “Female” button, let’s make the computer say “So is Mary Poppins”.

To accomplish all that, just type this HTML:

What sex are you?

<form>

<input type=button value="Male" onclick="alert('So is Frankenstein')">

<input type=button value="Female" onclick="alert('So is Mary Poppins')">

</form>

Here’s what each line accomplishes:

Since we want the Web page to begin by asking “What sex are you?”, the top line says “What sex are you?”

To create buttons, you must create a form to put them in, so the second line says <form>.

The next line says to create an input button labeled “Male”, which when clicked will do this command: create an alert box saying “So is Frankenstein”.

The next line says to create a similar input button labeled “Female”, which when clicked will do this command: create an alert box saying “So is Mary Poppins”.

The bottom line, </form>, marks the end of the form.


Notice these details:

After onclick, you put an equal sign, then a quotation mark, then any command written in JavaScript (or JScript), such as “alert”. The computer automatically knows that the onclick command uses JavaScript, so you don’t have to say <script>.

The JavaScript command must be in a pair of quotation marks. If you want to put a pair of quotation marks inside another pair of quotation marks, use a pair of single quotes (which look like apostrophes).

After onclick, instead of typing a JavaScript command, you can type several JavaScript commands, if you separate them by semicolons, like this:

onclick="x=4; y=2; alert(x+y)"

That would mean: if the button is clicked, make x=4, make y=2, and create an alert box showing their sum, 6.

When you create two buttons, the second button normally appears to the right of the first button. If you’d rather place the second button below the first button, say <br> before the second button to put it on a new line, like this:

<br><input type=button value="Female" onclick="alert('So is Mary Poppins')">

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Documentation

On page 325, I said you can write a comment in your HTML program by starting with the symbol “<!--” and ending with the symbol “-->”, like this:

<!--I wrote this program while drunk-->

But while you’re writing JavaScript (or JScript) program lines, which comes between <script> and </script>, you must write your comments differently, in JavaScript style: put each comment on a separate line that begins with //, like this:

//I wrote these JavaScript lines while even drunker

Emphasize JavaScript

To emphasize that your program is written in JavaScript (or a JavaScript clone such as JScript), you can say —

<script language="JavaScript">

or even say —

<script language="JavaScript" type="text/javascript">

instead of saying just <script>.

No JavaScript?

Most Web browsers understand JavaScript and JScript programs. But Web browsers that are very old or very primitive don’t understand JavaScript at all.

If your Web-page program contains a JavaScript program, but somebody who lacks JavaScript tries to view your Web page, the page will look very messed up, and the person might even see your raw JavaScript code, including equal signs and words such as “document.write”.

To make sure such a person doesn’t see your raw code on the Web page, say this instead of just <script> —

<script>

<!--

and say this instead of just </script>:

//-->

</script>

Also, warn the JavaScript-deprived person that your page requires JavaScript, by putting this line below the </script> line:

<noscript>This page requires JavaScript</noscript>

Here’s what that line accomplishes: if the person has no JavaScript, the Web page will say “This page requires JavaScript”.