Writing Your First Program In JavaScript

In This Chapter

Adding JavaScript code to your pages Setting up your environment for JavaScript Creating variables
Input and output with modal dialog boxes Using concatenation to build text data Understanding basic data types Using string methods and properties Using conversion functions eb pages begin with XHTML code. This basic code provides the framework. CSS adds decoration to the basic structure, but to make your pages literally sing and dance, you’ll need to learn a programming language.
The JavaScript language is a very popular first language, because it’s designed to interact with Web pages, and it’s already built into most Web browsers. It’s reasonably easy to learn, and it’s very powerful.
The whole idea of learning a programming language might seem intimidating, but don’t worry. Programming isn’t really that hard. I show you exactly how to get started in this chapter. You’ll be coding like a pro in a very short time.

Becoming a Programmer

JavaScript is a programming language first developed by Netscape communications. It is now standard on nearly every browser. There are a few things you should know about JavaScript right away:
‘ It’s a real programming language. Sometimes people who program in other languages such as C++ and VB.NET scoff at JavaScript and claim it’s not a “real” programming language because it lacks some features. These features (particularly the ability to communicate with the local file system) were left out on purpose to keep JavaScript safe. (You’re introduced to some AJAX alternatives that provide access to these features in the last half of this topic.) JavaScript is a real language, and it’s a very good place to start programming.
‘ It’s not Java. There is another popular programming language called Java (without the script part), which is also used for Web programming. JavaScript and Java are completely different languages (despite the similar names). Make sure you don’t go onto a Java forum and start asking JavaScript questions. Those Java programmers can be kind of snooty and superior. (They shouldn’t be; I program in Java, too. It’s just a language.)
‘ It’s a scripting language. JavaScript is a pretty easy language to get to know. It isn’t nearly as strict as certain other languages (I’m looking at you, Java), and it has a relatively relaxed view of things (for one, it’s less demanding about exactly what sort of data goes where). This lets you concentrate more on trying to solve your problem than worrying about exactly how your code is written. It’s still a programming language, so there are a few rules you must obey, but scripting languages such as JavaScript tend to be much more forgiving to beginners than the big monster languages.


Choosing a JavaScript editor

JavaScript (like XHTML and CSS) is really just text. You can modify your JavaScript code in the same editor you use for XHTML and CSS. If you used Aptana before (mentioned in Chapter 1) and liked it, you’re going to love the editor now. Of course, you can continue to use another editor if you prefer.
JavaScript is an entirely different language and uses a different syntax than HTML and CSS. It isn’t hard to learn, but there’s a lot to learn in any true programming language. Aptana has a number of really great features that help you tremendously when writing JavaScript code:
Syntax highlighting: Just like HTML and CSS, Aptana automatically adjusts code colors to help you see what’s going on in your program. As you see later in this chapter, this can be a big benefit when things get complicated.
Code completion: When you type in the name of an object, Aptana provides you with a list of possible completions. This can be really helpful, so you don’t have to memorize all the details of the various functions and commands.
Help files: The My Aptana page (available from the File menu if you’ve dismissed it) has links to really great help pages for HTML, CSS, and JavaScript. The documentation is actually easier to read than some of what you’ll find on the Web.
Integrated help: Hover the mouse pointer over a JavaScript command or method and a nifty little text box pops up, explaining exactly how it works. Often the box includes an example or two.
Error warnings: When Aptana can tell something is going wrong, it tries to give you an error message and places a red squiggly line (like the ones spellcheckers use) under the suspect code.
I’m unaware of a better JavaScript editor at any price, and Aptana is free, so there’s just not a good reason to use anything else. Of course, you can use any text editor you like if you don’t want or need these features.
There’s one strange characteristic I’ve noticed in Aptana: The Preview tab isn’t as reliable a technique for checking JavaScript code as it is for XHTML and CSS. I find it better to run the code directly in my browser or use the Run button to have Aptana run it in the external browser for me.

Picking your test browser

In addition to your editor, you should carefully choose your browser based on how it works when you’re testing JavaScript code.
All the major browsers support JavaScript, and it works relatively similarly across the browsers (at least until things get a bit more advanced). However, all browsers are not equal when it comes to testing your code.
Things will go wrong when you write JavaScript code, and the browser is responsible for telling you what went wrong. Firefox is way ahead of IE when it comes to reporting errors. Firefox errors are much easier to read and understand, and Firefox supports a feature called the JavaScript console (described in Chapter 4) that makes it much easier to see what’s going on. If at all possible, use Firefox to test your code, and then check for discrepancies in IE.
Chapter 4 gives you more about finding and fixing errors — and some great tools in Firefox and Aptana to make this important job easier.
That’s enough preliminaries. Pull out your editor, and start writing a real program. It’s simple enough to get started. The foundation of any JavaScript program is a standard Web page.

Adding a script to your page

The context of JavaScript programs is Web pages, so begin your JavaScript journey by adding some content to a basic Web page. If you aren’t familiar
with XHTML or CSS (the languages used for basic Web development), please review the bonus chapters available on either of the two Web sites dedicated to this topic  or look into a more complete reference like HTML, XHTML, and CSS All-in-One Desk Reference For topic.
It’s pretty easy to add JavaScript code to your pages. Figure 2-1 shows the classic first program in any computer language.
This page has a very simple JavaScript program in it that pops up the phrase “Hello, World!” in a special element called a dialog box. It’s pretty cool.
Here’s an overview of the code, and then I’ll explain all the details step by step.
tmp7B1_thumb_thumb
As you can see, there’s nothing in the HTML body in this page at all. You can (and will) incorporate JavaScript with XHTML content later. For now, though, you can simply place JavaScript code in the head area of your Web page in a special tag and make it work.

Hello, World?

There’s a long tradition in programming languages that your first program in any language should simply say “Hello, World!” and do nothing else. There’s actually a very good practical reason for this habit. Hello World is the simplest possible program you can write that you can prove works. Hello World programs are used to
help you figure out the mechanics of the programming environment — how the program is written, what special steps you have to do to make the code run, and how it works. There’s no point in making a more complicated program until you know you can get code to pop up and say hi.
A JavaScript program caused this little dialog box to pop up!
Figure 2-1:
A JavaScript program caused this little dialog box to pop up!

Embedding your JavaScript code

JavaScript code is placed in your Web page via the <script> tag. JavaScript code is placed inside the <script></script> pair. The <script> tag has one required attribute, type, which will usually be text/javascript. (Other types are possible, but they are rarely used.)
The other funny thing in the code in the previous section is that crazy CDATA stuff. Immediately inside the <script> tag, the next line is
tmp7B3_thumb_thumb
This bizarre line is a special marker explaining that the following code is character information, and shouldn’t be interpreted as XHTML. The end of the script finishes off the character data marker with this code:
tmp7B4_thumb_thumb
In modern browsers, it’s a good idea to mark off your JavaScript code as character data. If you don’t, the XHTML validator will sometimes get confused and claim you have errors when you don’t.
That CDATA business is bizarre. It’s hard to memorize, I know, but just type it a few times, and you’ll own it.
A lot of older topics and Web sites do not include the character data trick, but it’s well worth mastering. You’ve invested too much effort into building standards-compliant pages to have undeserved error messages pop up because the browser mistakes your JavaScript for badly-formatted XHTML.

Creating comments

As with XHTML and CSS, JavaScript comments are important to include. Because programming code can be more difficult to decipher than XHTML or CSS, it’s even more important to comment your code in JavaScript than it is in those other two environments. The comment character in JavaScript is two slashes (//). The browser ignores everything from the two slashes to the end of the line. You can also use a multi-line comment (/* */) just like the one in CSS.

Using the alert() method for output

There are a number of ways to output data in JavaScript. In this example, I use the alert() method. This technique pops up a small dialog box containing text for the user to read. The alert box is an example of a modal dialog box. Modal dialog boxes interrupt the flow of the program until the user pays attention to them. Nothing else will happen in the program until the user acknowledges the dialog box by clicking the OK button. The user can’t interact with the page until after clicking the button.
Modal dialog boxes might seem a bit rude. In fact, you probably won’t use them much once you learn some other input and output techniques. The fact that the dialog box demands attention makes it a very easy tool to use when you start programming. When you’ve got the basic programming ideas under your belt, I show you more elegant ways to communicate with the Web page.

Adding the semicolon

Each command in JavaScript ends with a semicolon (;) character. The semicolon in most computer languages acts like the period in English: It indicates the end of a logical thought. Usually each line of code is also one line in the text editor.
To tell the truth, JavaScript usually works fine if you leave out the semicolons, but you should add them anyway because they can clarify your meaning. Besides, most other languages (such as PHP, introduced in Chapter 14) require semicolons. You might as well start a good habit now.

Introducing Variables

Computer programs get their power by working with information. Figure 2-2 shows a program that gets data from the user and uses it in a customized greeting.
The program asks for the user's name.
Figure 2-2:
The program asks for the user’s name.
This program introduces a new kind of dialog box that allows the user to enter some data. The information is stored in the program for later use. Figure 2-3 shows the first part of the response at the top. The user must click OK to get the rest of the greeting in a second alert dialog box, as shown at the bottom of Figure 2-3.
A two-dialog box response to user input.
Figure 2-3:
A two-dialog box response to user input.
The output might not seem that incredible, but take a look at the source code to see what’s happening:
tmp7B7_thumb_thumb

Creating a variable for data storage

This program is interesting because it allows user interaction. The user can enter a name that is stored in the computer and then returned in a greeting. The key to this program is a special element called a variable. Variables are simply places in memory for holding data. Any time you want a computer program to “remember” something, you can create a variable and store your information in it.

Variables typically have the following characteristics:

The var statement. Indicates you are creating a variable with the var command.
A name. When you create a variable, you are required to give it a name.
An initial value. It’s useful to give each variable a value immediately
A data type. JavaScript automatically determines the type of data in a variable (more on this later), but you should still be clear in your mind about what type of data you expect a particular variable to contain.

Asking the user for information

Variables are more interesting when they contain information. JavaScript has a simple tool called the prompt, which allows you to easily ask a question and store the answer in a variable. Here’s the relevant line from prompt.html:
tmp7B8_thumb_thumb

The prompt statement does several interesting things:

It pops up a dialog box. The prompt() method creates a modal dialog box much like the alert technique discussed earlier.
It asks a question. The prompt command expects you to ask the user a question.
It provides space for a response. There is a space in the dialog box for the user to type a response of some kind, and buttons to indicate that the user is finished or wants to cancel the operation.
It passes the information to a variable. The purpose of a prompt command is to get data from the user, so prompts are nearly always connected to a variable. When the code is finished, the variable will contain the indicated value.

Responding to the user

This program uses the alert() method to begin a greeting to the user. The first alert works just like the one from the hello World program:
tmp7B9_thumb_thumb
The content of the parentheses is the text you want the user to see. In this case, you want the user to see the literal value “Hi”.

The second alert statement is a little bit different:

tmp7B10_thumb_thumb
This alert statement has a parameter with no quotes. Since there are no quotes, JavaScript understands you don’t really want to say the text “person”. Instead, it looks for a variable named person, and returns the value of that variable.
So the variable can take any name, store it, and return a customized greeting.

Using Concatenation to Build Better Greetings

It seems a little awkward to have the greeting and the person’s name on two different lines. Figure 2-4 shows a better solution. The program asks for a name again, and stores it in a variable. This time, the greeting is combined into one alert dialog box, and it looks a lot better:
Now there's just one dialog box response to the user's input.
Figure 2-4:
Now there’s just one dialog box response to the user’s input.
The secret to Figure 2-4 is one of those wonderful gems of the computing world: a really simple idea with a really complicated name. Take a look at the code and you’ll see that combining variables with text is not all that complicated:
tmp7B12_thumb_thumb
For the sake of brevity, I’ve only included the <script> tag and its contents; the rest of this page is a standard blank XHTML page.  I use this approach throughout this chapter, but I also include a comment in each JavaScript snippet to indicate where you can get the entire file on the Web site.

Concatenation and your editor

The hard part about concatenation is figuring out which part of your text is a literal value and which part is a string. It won’t take long before you start going cross-eyed trying to understand where the quotes go.
Modern text editors (like Aptana) have a wonderful feature that can help you here. They color different kinds of text in different colors. By default, Aptana colors variable names black, and literal text dark green (at least when you’re in JavaScript — in HTML, literal text is in blue).
Personally, I find it hard to differentiate the dark green from black, so I changed the Aptana color scheme: I have it make string literals blue whether I’m in JavaScript or HTML. With this setting in place, I can easily see what part of the statement is literal text and what’s being read as a variable name. That makes concatenation a lot easier.
To change the color scheme in Aptana, click Window Preferences. You’ll see an expandable outline in the resulting dialog box. Click Aptana EditorsO JavaScript Editor Colors. You can then scroll down and find color settings for any type of data. I found “string” (another term for text) under “literals” and changed the color of my text strings from dark green to blue.
If you make a mistake, there’s a button to revert back to the default values.
Most editors that have syntax highlighting allow you to change settings to fit your needs. Don’t be afraid to use these tools to help you program better.

Comparing literals and variables

In this program there are really two different kinds of text. The whole expression “Hi there, ” is a literal text value. That is, you really mean to say “Hi there.” On the other hand, person is a variable; you can put any person’s name in it. You can combine literal values and variables in one phrase if you want:
tmp7B13_thumb_thumb
The secret to this code is to follow the quotes. “Hi there, ” is a literal value, because it is in quotes. In this line, person is a variable name (because it is not in quotes) and “I” is a literal value. You can combine any number of text snippets together with the plus sign as shown in the preceding code.
Using the plus sign to combine text is called concatenation. (I told you it was a complicated word for a simple idea.)

Including spaces in concatenated phrases

You might be curious about the extra space between the comma and the quote in the output line:
tmp7B14_thumb_thumb
This is important because you want the output to look like a normal sentence. If you don’t have the space, the computer won’t add one, and the output would look like:
Hi there,Benjamin!
Be sure to construct the output as it should look on-screen, including spaces and punctuation.

Understanding the string Object

The person variable used in the previous program is designed to hold text. Programmers (being programmers) devised their own mysterious term to refer to text. In programming, text is referred to as string data.
The term string comes from the way text is stored in computer memory. Each character is stored in its own cell in memory, and all the characters in a word or phrase reminded the early programmers of beads on a string. (Surprisingly poetic for a bunch of geeks, huh?)

Introducing object-oriented programming (and cows)

JavaScript (and many other modern programming languages) use a powerful model called object-oriented programming (OOP). This style of programming has a number of advantages. Most important for beginners, it allows you access to some very powerful objects that do interesting things out of the box.
Objects are used to describe complicated things that can have a lot of characteristics — for instance, a cow. You can’t really put an adequate description of a cow in an integer variable.
In many object-oriented environments, objects can have these characteristics (imagine a cow object for the examples):
Properties: Characteristics about the object, such as breed and age. Methods: Things the objects can do, such as moo() and give Milk() . Events: Stimuli the object responds to, such as on Tip() .
Each of these ideas will be described as they are needed, as not all objects support all these characteristics.
If you have a variable of type cow, it describes a pretty complicated thing. This thing might have properties, methods, and events. All could be used together to build a good representation of a cow. (Believe it or not, I’ve built cow programming constructs more than once in my life — and you thought programming was dull.)
Most variable types in JavaScript are actually objects — and most JavaScript objects have a full complement of properties and methods (many even have event handlers). When you get a handle on how all these things work, you’ve got a powerful and compelling programming environment.
Okay, before somebody sends me some angry e-mails, I know there is some debate about whether JavaScript is a truly object-oriented language. I’m not going to get into the (frankly boring and not terribly important) details in this topic. We’re going to call it object-oriented for now, because it’s close enough for beginners. If that bothers you, you can refer to JavaScript as an object-based language. Nearly everyone agrees with that. More information on this topic is throughout the topic as you learn how to build your own objects in Chapter 5 and how to use HTML elements as objects in Chapter 6.

Investigating the length of a string

When you assign text to a variable, JavaScript automatically treats the variable as a string object. The object instantly takes on the characteristics of a string object. Strings have a couple of properties, and a bunch of methods. The one interesting property (at least for beginners) is length. Look at the example in Figure 2-5 to see the length property in action:
This program reports the length of any text.
Figure 2-5:
This program reports the length of any text.
That’s kind of cool. The cooler part is the way it works. As soon as you assign a text value to a variable, JavaScript treats that variable as a string, and since it’s a string, it now has a length property. This property returns the length of the string in characters. Here’s how it’s done in the code:
tmp7B16_thumb_thumb
This code uses the length property as if it were a special subvariable. For example, person is a variable in the previous example — and person, length is the length property of the person variable. In JavaScript, an object and a variable are connected by a period (with no spaces).
The string object in JavaScript has only two other properties (constructor and prototype). Both of these properties are only needed for advanced programming, so I skip them for now.

Using string methods to manipulate text

The length property is kind of cool, but the string object has a lot more up its sleeve. Objects also have methods (things the object can do). Strings in JavaScript have all kinds of methods. Here’s a few of my favorites:
to Upper Case() : Makes an entirely uppercase copy of the string. to Lower Case(): Makes an entirely lowercase copy of the string. substring(): Returns a specific part of the string. index Of(): Determines if one string occurs within another.
The string object has many other methods, but I’m highlighting these because they’re useful for beginners. Many of the string methods — such as big() and font Color() — simply add HTML code to text. They aren’t used very often, because they produce HTML code that won’t validate, and they don’t really save a lot of effort anyway. Some of the other methods — such as search() , replace(), and slice() — use advanced constructs like arrays and regular expressions that aren’t necessary for beginners. (To learn more about working with arrays, see Chapter 5. You learn more about regular expressions in Chapter 7.)

Why are the first three characters (0, 3)?

The character locations for JavaScript (and most programming languages) will probably seem somewhat strange to you until you know the secret. You might expect text. substring(1,3) to return the first three characters of the variable text, yet I used text.substring(0,3) to do that job. Here’s why: The indices don’t correspond to
character numbers; instead, they are the indices between characters.
tmp7B17_thumb_thumb
So if I want the first three characters of the string “abcd”, I use substring(0,3). If I want the “cd” part, it’s substring(2,4).
Don’t take my word for it. Look up the JavaScript string object in the Aptana online help (or one of the many other online JavaScript references) and see what properties and methods it has.
Like properties, methods are attached to an object by using a period. Methods are distinguished by a pair of parentheses, which sometimes contains special information called parameters. Parameters are information that will be passed to the method so it can do its job. Some methods require parameters, and some do not. It all makes sense once you start using methods.

The best way to see how methods work is to check out some in action. Look at the code for string Methods.html:

tmp7B18_thumb_thumb
The output produced by this program is shown in Figure 2-6.
Here’s yet another cool thing about Aptana: When you type the term text. (complete with period), Aptana understands that you’re talking about a string variable and automatically pops up a list of all the possible properties and methods. (I wish I’d had that when I started doing this stuff.)
You can see from this code that methods are pretty easy to use. When you have a string variable in place, you can invoke the variable’s name, followed by a period and the method’s name. Some of the methods require more information to do their job. Here’s a look at the specifics:
to Upper Case() and to Lower Case() :Takes the value of the variable and converts it entirely to the given case. This is often used when you aren’t concerned about the capitalization of a variable.
index Of (substring): Returns the character position of the substring within the variable. If the variable doesn’t contain the substring, return the value -1.
substring(begin, end): Returns the substring of the variable from the beginning character value to the end.
String methods can be fun
Figure 2-6:
String methods can be fun

Understanding Variable Types

JavaScript isn’t too fussy about whether a variable contains text or a number, but the distinction is still important, because there is a difference in the way these things are stored in memory, and this difference can cause some surprising problems.

Adding numbers

To see what can go wrong when JavaScript misunderstands data types, try a little experiment. First, take a look at the following program (as usual for this chapter, I’m only showing the script part because the rest of the page is
blank):
tmp7B20_thumb_thumb
This program features three variables. I’ve assigned the value 5 to x, and 3 to y. I then add x + y and assign the result to a third variable, sum. The last line prints out the results, which are also shown in Figure 2-7.
This program (correctly) adds two numbers together.
Figure 2-7:
This program (correctly) adds two numbers together.
You can assign values to variables. It’s best to read the equals sign as “gets” so the first assignment should be read as “variable x gets the value 5.”
tmp7B22_thumb_thumb
Numeric values are not enclosed in quotes. When you refer to a text literal value, it is always enclosed in quotes. Numeric data (like the value 5) are not placed in quotes.
You can add numeric values. Since x and y both contain numeric values, you can add them together.
The results of an operation can be placed in a variable. The result of the calculation x + y is placed in a variable called sum.
Everything works as expected. The program behaves in the way you intended it to. That’s important because it’s not always true as you’ll see in the next example — I love writing code that blows up on purpose!

Adding the user’s numbers

The natural extension of the add Numbers.html program would be a feature that allows the user to input two values and then return the sum. This could be the basis for a simple adding machine. Here’s the JavaScript code:
tmp7B23_thumb_thumb
This code seems reasonable enough. It asks for each value and stores them in variables. It then adds the variables up and returns the results, right? Well, look at Figure 2-8 and you’ll see a surprise.
Something’s obviously not right here. To understand the problem, you need to see how JavaScript makes guesses about data types.
Wait a minute . . . 3 + 5 = 35?
Figure 2-8:
Wait a minute . . . 3 + 5 = 35?

The trouble with dynamic data

Ultimately, all the information stored in a computer, from music videos to e-mails, is stored as a bunch of ones and zeroes. The same value 01000001 could mean all kinds of things: it might mean the number 65 or the character A. (In fact, it does mean both of those things in the right context.) The same binary value might mean something entirely different if it’s interpreted as a real number, a color, or a part of a sound file.
The theory isn’t critical here, but one point is really important: Somehow the computer has to know what kind of data is stored in a specific variable. Many languages (like C and Java) have all kinds of rules about this. If you create a variable in one of these languages, you have to define exactly what kind of data will go in the variable — and you can’t change it.
JavaScript is much more easygoing about variable types. When you make a variable, you can put any kind of data in it that you want. In fact, the data type can change. A variable can contain an integer at one point and the same variable might contain text in another part of the program.
JavaScript uses the context to determine how to interpret the data in a particular variable. When you assign a value to a variable, JavaScript puts the data in one of the following categories:
Integer: Integers are whole numbers (no decimal part). They can be positive or negative values.
‘ Floating-point number: A floating-point number has a decimal point like 3.14. Floating-point values can also be expressed in scientific notation like 6.02e23 (Avagadro’s number: 6.02 times 10 to the 23rd). Floating point numbers can also be negative.
Boolean: A Boolean value can only be true or false.
String: Text is usually referred to as “string” data in programming languages. String values are usually enclosed in quotes.
Arrays and objects: These are more complex data types you can ignore for now. They are covered in depth in Chapter 5.
These different data types are necessary because the computer uses different techniques to store different types of data into the binary format that all computer memory ultimately uses. Most of the time, when you make a variable, JavaScript guesses right and you have no problems. But sometimes JavaScript makes some faulty assumptions and things go wrong.

The pesky plus sign

I’ve used the plus sign in two different ways throughout this chapter. The following code uses the plus sign in one way:
tmp7B25_thumb_thumb
In this code, x and y are text variables. The result = x + y line is interpreted as “concatenate x and y,” and the result will be “Hi, there!”.

Here’s the strange thing: The following code is almost identical:

tmp7B26_thumb_thumb
The behavior of the plus sign is different here, even though the statement result = x + y is identical!
In this second case, x and y are numbers. The plus operator has two entirely different jobs. If it’s surrounded by numbers, it adds. If it’s surrounded by text, it concatenates! Automatically. (Hoo boy.)
That’s what happens to the first adding-machine program (the one that blows up): When the user enters data in prompt dialog boxes, JavaScript assumes the data is text. So when I try to add x and y, it “helpfully” concatenates instead.
There’s a fancy computer-science word for this phenomenon (an operator doing different things in different circumstances). Those Who Care About Such Things call this an overloaded operator. Smart people sometimes have bitter arguments about whether overloaded operators are a good idea or not, because they can cause problems like the program concatenating when you think it will add. Overloaded operators can also make things easier in other contexts. I’m not going to enter into that debate here. It’s not a big deal, as long as you can see the problem and fix it when it occurs.

Changing Variables to the Desired Type

If JavaScript is having a hard time figuring out what type of data is in a variable, you can give it a friendly push in the right direction with some handy conversion functions as shown in Table 2-1.

Table 2-1 Variable Conversion Functions
Function From To Example Result
parseInt() String Integer parseInt(“23″) 23
parseFloat() String Floating- parseFloat 21.5
point (“21.5″)
toString() Any variable String myVar.toString() varies
eval() Expression Result eval(“5 + 3″) 8
Math.ceil() Floating- Integer Math.ceil(5.2) 6
Math.floor() point Math.floor(5.2) 5
Math.round Math.round(5.2) 5

Using variable conversion tools

The conversion functions are incredibly powerful, but you only need them if the automatic conversion causes you problems. Here’s how they work:
parselnt(): Used to convert text to an integer. If you put a text value inside the parentheses, the function returns an integer value. If the string has a floating-point representation (“4.3″ for example), an integer value (4) will be returned.
parse Float(): Converts text to a floating-point value.
to String(): Takes any variable type and creates a string representation. Note that it isn’t usually necessary to use this function, because it’s usually invoked automatically when needed.
eval(): This is a special method that accepts a string as input. It then attempts to evaluate the string as JavaScript code and return the output. You can use this for variable conversion or as a simple calculator — eval(“5 + 3″) will return the integer 8.
Math.ceil(): One of several methods of converting a floating-point number to an integer. This technique always rounds upward, so Math. ceil(1.2) will be 2, and Math.ceil(1.8) will also be 2.
Math.floor(): Similar to Math.ceil, except it always rounds downward, so Math.floor(1.2) and Math.floor(1.8) will both evaluate to 1.
Math.round(): Works like the standard rounding technique used in grade school. Any fractional value less than .5 will round down, and greater than or equal to .5 will round up, so Math.round(1.2) is 1, and Math.round(1.8) is 2.

Fixing the addlnput code

With all this conversion knowledge in place, it’s pretty easy to fix up the add Input program so it works correctly. Just use parse Float() to force both inputs into floating-point values before adding them. Note that you don’t have to convert the result explicitly to a string. That’s done automatically when you invoke the alert() method:
tmp7B27_thumb_thumb
You can see the program works correctly in Figure 2-9.
Conversion methods allow you to ensure the data is in exactly the format you want.
Now the program asks for input and correctly returns the sum.
Figure 2-9:
Now the program asks for input and correctly returns the sum.

Next post:

Previous post: