Hour 5. Data Processing with Numbers and Words

Without an in-depth knowledge of characters, strings, and numbers, you won’t be able to understand any programming language. This doesn’t mean that you must be a math whiz or an English major. You must, however, understand how languages such as JavaScript represent and work with such data.

In this hour, you will learn more about how JavaScript performs its mathematical calculations. In addition, you will learn how JavaScript represents and works with strings. Along the way, you will discover functions and powerful built-in routines that perform many of the programming chores for you.

The highlights of this hour include

Image Merging strings together

Image Understanding internal representation of strings

Image Mastering the programming operators

Image Digging into JavaScript’s functions

Strings Revisited

Like most programming languages, JavaScript has excelled in their support of strings. Hardly any programming language before BASIC was created in the 1960s supported string data except in a rudimentary form. BASIC was created for beginners, but it offered advanced support for strings.

Even since the first BASIC language, programming languages have been slow to adopt string support beyond a rudimentary level. C++, one of the newer programming languages of the past 50 years and one of the most used, did not directly support strings. To work with strings in C++ (and its earlier rendition C), programmers had to do some fancy footwork to get around the fact that the fundamental string data type was not supported.

Merging Strings

You can merge or concatenate (programmers rarely use a simple word when a longer word will confuse more people) two strings together simply by placing a plus sign between them. Without going into too much detail, Listings 4.4 and 4.5 in Hour 4, “Getting Input and Displaying Output,” used string concatenation before outputting the result to the screen.

The ASCII Table

To fully understand strings, you must understand how your computer represents characters internally. A concept that will come into major play while you program in any language is the ASCII table (pronounced ask-ee). Although the reason for the ASCII table and how to take advantage of your knowledge of the ASCII table will increase as you hone your programming skills, you should take a few moments for an introduction to this important character-based table.

Years ago, somebody wrote all the various combinations of eight binary 1s and 0s, from 00000000 to 11111111, and assigned a unique character to each one. The table of characters was standardized and is known today as the ASCII table. Table 5.1 shows a partial listing of the ASCII table that contains 256 entries. ASCII stands for American Standard Code for Information Interchange. Some ASCII tables use only the last seven bits (called the 7-bit ASCII table) and keep the far left-hand bit off. As you might surmise, a bit is a 1 or a 0. Eight bits form a byte, which is a character in computer terminology due to the ASCII table. Seven-bit ASCII tables cannot represent as many different characters as can today’s 8-bit ASCII tables.

Image

TABLE 5.1 Every character possible has its own unique ASCII value.

Each ASCII value has a corresponding decimal number associated with it. These values are shown at the right of the eight-bit values in Table 5.1. Therefore, even though the computer represents the character “?” as 00111111 (two off switches with six on switches), you can refer, through programming, to that ASCII value as 63 and your computer will know you mean 00111111. One of the advantages of high-level programming languages is that they often let you use the easier (for people) decimal values and the programming language converts the value to the 8-bit binary value used inside the computer.

As you can tell from the ASCII values in Table 5.1, every character in the computer, both uppercase and lowercase letters, and even the space, has its own unique ASCII value. The unique ASCII code is the only way that the computer has to differentiate characters.

Every microcomputer uses the ASCII table. Large mainframe computers use a similar table called the EBCDIC table (pronounced eb-se-dik). EBCDIC stands for Extended Binary Coded Decimal Interchange Code. The ASCII table is the fundamental storage representation of all data and programs that your computer manages. A new coding scheme called Unicode is now beginning to see some use. Unicode spans far more than the 256 character limit of the ASCII or EBCIDIC tables to take into account languages such as the Japanese-based kanji and others that require numerous characters to represent. Unicode assigns hundreds of numbers to hundreds and even thousands of possible characters depending on the language being represented.

When you press the letter A, that A is not stored in your computer; rather, the ASCII value of the letter A is stored. As you can see from the ASCII values in the previous table, the letter A is represented as 01000001 (all eight switches except two are off in every byte of memory that holds a letter A).


Tip

The ASCII table is not very different from another type of coded table you may have heard of. Morse code is a table of representations for letters of the alphabet. Instead of 1s and 0s, the code uses combinations of dashes and dots to represent characters.


As Figure 5.2 shows, when you press the letter A on your keyboard, the A does not go into memory, but the ASCII value of 01000001 does. The computer keeps that pattern of on and off switches in that memory location as long as the A is to remain there. As far as you are concerned, the A is in memory as the letter A, but now you know exactly what happens.

Image

FIGURE 5.2 The letter A is not an A after it leaves the keyboard.

As Figure 5.2 illustrates, when you print a document from your word processor, the computer prints each “character” stored in that memory location; the computer’s CPU sends the ASCII code for the letter A to the printer. Just before printing, the printer knows that it must make its output readable to people, so it looks up 01000001 in its own ASCII table and prints the A to paper. From the time the A left the keyboard until right before it printed, it was not an A at all, but just a combination of eight 1s and 0s that represents an A.

Performing Math with JavaScript

JavaScript performs mathematical calculations in the same way as most programming languages. Therefore, once you understand the way JavaScript calculates, you’ll understand how virtually every other computer language calculates. Table 5.2 lists the JavaScript math operators with which you should familiarize yourself.

Image

TABLE 5.2 JavaScript math operators are simple.

The order of the operators in Table 5.2 is important. If more than one of these operators appears in an expression, JavaScript doesn’t always calculate the values in a left-to-right order. In other words, the expression

v = 5 + 2 * 3

stores the value 11 in v, not 21 as you might first guess. JavaScript doesn’t perform calculations in a left-to-right order, but rather in the order given in Table 5.2. Because multiplication appears before addition in the table, JavaScript computes the 2 * 3 first, resulting in 6; it then computes the answer to 5 + 6 to get the result of 11.


Tip

The order in which operators are evaluated is often called operator precedence. Just about every programming language computes expressions based on a precedence table. Different programming languages might use different operators from the ones shown in Table 5.2, although almost all of them use parentheses and the primary math operators (*, /, +, and -) in the same way as JavaScript does.


Parentheses have the highest operator precedence. Any expression enclosed in parentheses is calculated before any other part of the expression. The statement

v = (5 + 2) * 3

does assign the value of 21 to v because the parentheses force the addition of 5 and 2 before its sum of 7 is multiplied by 3.

Unlike some programming languages, JavaScript does not have an exponentiation operator to raise a number to a particular power. To do that, you would have to call Math.pow(a, b), with a being the number multiplied by itself b times. For example, if you wanted to know 4 x 4 x 4, sometimes written as 4^3, you would call Math.pow(4, 3), which would return the answer of 64.

You can also raise a number to a fractional power with the Math.pow method. For example, the statement

x = Math.pow(81, 0.5);

raises 81 to the one-half power, in effect taking the square root of 81. If this math is getting deep, have no fear; some people program in JavaScript for years and never need to raise a number to a fractional power. But if you need to, you can thank JavaScript for doing the heavy lifting for you.

The forward slash (/) divides one number into another. The statement

d = 3 / 2 ;

assigns 1.5 to d.

How Computers Really Do Math

At their lowest level, computers cannot subtract, multiply, or divide. Neither can calculators. The world’s largest and fastest supercomputers can only add—that’s it. They perform the addition at the bit level. Binary arithmetic is the only means by which any electronic digital-computing machine can perform arithmetic.

The computer makes you think it can perform all sorts of fancy calculations because it is lightning fast. The computer can only add, but it can do so very quickly.

Suppose you want the computer to add seven 6s together. If you asked the computer (through programming) to perform the calculation

6 + 6 + 6 + 6 + 6 + 6 + 6

the computer would return the answer 42 immediately. The computer has no problem performing addition. The problems arise when you request that the computer perform another type of calculation, such as this one:

42 − 6 − 6 − 6 − 6 − 6 − 6 − 6

Because the computer can only add, it cannot do the subtraction. However (and this is where the catch comes in), the computer can negate numbers. That is, the computer can take the negative of a number. It can take the negative of 6 and represent (at the bit level) negative 6. After it has done that, it can add −6 to 42 and continue doing so seven times. In effect, the internal calculation becomes this:

42 + (−6) + (−6) + (−6) + (−6) + (−6) + (−6) + (−6)

Adding seven −6s produces the correct result of 0. In reality, the computer is not subtracting. At its bit level, the computer can convert a number to its negative through a process known as 2’s complement. The 2’s complement of a number is the negative of the number’s original value at the bit level. The computer has in its internal logic circuits the ability to rapidly convert a number to its 2’s complement and then carry out the addition of negatives, thereby seemingly performing subtraction.


Note

Here’s another kind of 2’s complement: That’s a very fine two you have there.


Because the computer can add and simulate subtraction (through successive adding of negatives), it can simulate multiplying and dividing. To multiply 6 times 7, the computer actually adds 6 together seven times and produces 42. Therefore,

6 * 7

becomes this:

6 + 6 + 6 + 6 + 6 + 6 + 6

To divide 42 by 7, the computer subtracts 7 from 42 (well, it adds the negative of 7 to 42) until it reaches 0 and counts the number of times (6) it took to reach 0, like this:

42 + (−7) + (−7) + (−7) + (−7) + (−7) + (−7)

The computer represents numbers in a manner similar to characters. As Table 5.3 shows, numbers are easy to represent at the binary level. After numbers reach a certain limit (256 to be exact), the computer will use more than one byte to represent the number, taking as many memory locations as it needs to represent the extent of the number. The computer, after it is taught to add, subtract, multiply, and divide, can then perform any math necessary as long as a program is supplied to direct it.

Image

TABLE 5.3 The first 20 numbers can be represented in their binary equivalents.


Note

The first 255 binary numbers overlap the ASCII table values. That is, the binary representation for the letter A is 01000001, and the binary number for 65 is also 01000001. The computer knows by the context of how your programs use the memory location whether the value is the letter A or the number 65.


To see an example of what goes on at the bit level, follow this example to see what happens when you ask the computer to subtract 65 from 65. The result should be 0, and as you can see from the following steps, that is exactly what the result is at the binary level:

1. Suppose you want the computer to calculate the following:
 65
−65

2. The binary representation for 65 is 01000001 and the 2’s complement for 65 is 10111111 (which is −65 in computerese). Therefore, you are requesting that the computer perform this calculation:
 01000001
+10111111

3. Because a binary number cannot have the digit 2 (there are only 0s and 1s in binary), the computer carries 1 any time a calculation results in a value of 2; 1 + 1 equals 10 in binary. Although this can be confusing, you can make an analogy with decimal arithmetic. People work in a base-10 numbering system. Binary is known as base-2. There is no single digit to represent 10; we have to reuse two digits already used to form 10, namely 1 and 0. In base 10, 9 + 1 is 10. Therefore, the result of 1 + 1 in binary is 10 or “0 and carry 1 to the next column.”
 01000001
+10111111
100000000

4. Because the answer should fit within the same number of bits as the two original numbers (at least for this example—your computer may use more bits to represent numbers), the ninth bit is discarded, leaving the 0 result. This example shows that binary 65 plus binary negative 65 equals 0, as it should.


Tip

You can see a complete ASCII table at this web address: http://www.AsciiTable.com/


Using the ASCII Table

By understanding the ASCII table available, you can print any character by referring to its ASCII number. For instance, the capital letter A is number 65. The lowercase a is 97. Since you can type letters, numbers, and some special characters on your keyboard, the ASCII table is not needed much for these. However, you cannot use the keyboard to type the Spanish Ñ or the cent sign (¢), under normal circumstances. You print these with the String.FromCharCode method, which converts a number to its corresponding ASCII character. The format of String.FromCharCode is

String.FromCharCode(ASCII number)

The following document.write statement prints a capital N with a tilde over it, followed by a lowercase N, also with a tilde, and then the upside-down question mark that begins questions in Spanish. These characters would come in handy if you decide to translate your website to Spanish:

document.write(String.fromCharCode(209,241,191));

Here is the output:

Ññ¿

If you want to covert more than one character at a time, just separate the numbers with commas in the call to String.fromCharCode().

The first 31 ASCII codes represent nonprinting characters. Nonprinting characters cause an action to be performed instead of producing characters.

Overview of Methods

Methods are built-in routines that manipulate numbers, strings, and output. You can accomplish some pretty cool goals with string functions, but before you do, you need to understand a bit about arrays, as they will help you better use strong methods.

Understanding Arrays

Just as words and sentences are a collection of single letters, strings are a collection of characters, including words, spaces, letters, and any other special characters you choose to type or add using the ASCII function discussed earlier in this lesson. When you assign a string to a variable, such as

var hometown = "Salt Lake City, Utah"

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

alert(hometown);

as you can probably guess, your output will be a dialog box displaying

Salt Lake City, Utah

What is probably not obvious is what would happen if you called the alert method sending it hometown[3], such as

alert(hometown[3]);

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

t

Now you may have figured out that the number in brackets would refer to a specific letter or character in the string. (Good job if you did!) But even then you might think, why not the letter l? After all, it is the third character in the name of the city. While that is true, JavaScript (and most 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 may be wondering what character corresponds to hometown[4]. It is the space, with the L being 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.

This may seem confusing, but understanding arrays is important for almost every programming language. (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 your strings corresponds to a specific number and that if you’re counting them to figure it out, start with 0 and include all spaces, characters, letters, and numbers.

The next sections cover some of JavaScript’s string and math methods.

String Methods

Once you’ve defined a string, you can then access some built-in JavaScript methods to alter your strings. This section will not cover all the string methods, just some of the more interesting ones. Feel free to explore online of a JavaScript tutorial to cover some of the others.

Making strings all capital or all lowercase letters

Two methods can be used to take a string and change the case of all the letters. Any non-letter characters are just ignored. The two methods, toLowerCase() and toUpperCase(), will create a new string, leaving the original string untouched. Taking the previous example, if the variable hometown is equal to “Salt Lake City, Utah”, the following two calls

newtown1 = hometown.toLowerCase();

newtown2 = hometown.toUpperCase();

will result in newtown1 holding the string “salt lake city, utah” and newtown2 holding the string “SALT LAKE CITY, UTAH.” The original string remains the same.

The string methods discussed in this section must always be called with a period (.) between the name of the string and the specific method. You’ve already been using this format, specifically with document.write, but instead of a general top-level object-like document, you are using the method of a specific object you created (in this case a string variable). You’ve also already seen this with the Math.pow method of generating exponential results.

Replacing part of a string

Another valuable string function is one that lets you replace part of a string. Say the good folks of Utah decide to be more health-conscious and rename their capital Blue Lake City. You can use the replace() method to create a new string that switches words in a string. You can either make a new string as demonstrated in the previous section, or overwrite your existing string. If hometown is still equal to “Salt Lake City, Utah”, the code line

hometown = hometown.replace(“Salt”, “Blue”);

would result in hometown now being equal to “Blue Lake City, Utah”. You don’t have to replace entire words, either.

hometown = hometown.replace(“lt”, “lty”);

would result in hometown now being equal to “Salt Lake City, Utah. One additional note about replace. It only changes the first instance it finds of the substring you were trying to replace. So if your hometown was “New York, New York”, calling

hometown = hometown.replace(“New”, “Old”);

would result in hometown being equal to “Old York, New York”. If you wanted to change the “New” in the state as well, you’d have to call replace a second time. These methods are powerful and useful, but you should experiment with them in order to ensure you get the intended results.

Other valuable string methods include length, which returns the number of characters in a string; indexOf, which finds where a specific value occurs in a string; lastIndexOf, which finds the last time a specific value occurs in a string; split, which breaks a string into several smaller strings (useful to take a sentence and break it by spaces, so you get each individual word); and substr, which will make a substring based on the numbers you provide (for example, if you provided “Salt Lake City, Utah,” and 5, 11, the method would return “Lake Ci” as the substring). Some of these may seem to have little value, but as you develop scripts and programs, you’ll find them more useful than you’d initially guess.

Numeric Functions

There are several functions supplied by JavaScript that perform math routines, and this section introduces you to some of those. Two, parseInt() and parseFloat(), were already covered and are a great way to ensure that numbers are not mistaken for strings. Lots of your own code is saved if you use these functions.

One common numeric function is the Math.floor() method. Math.floor() returns the integer whole value of the numbers you put in the parentheses. If you put a decimal number inside the parentheses, Math.floor() converts it to an integer. For example,

document.write(Math.floor(8.93));

puts an 8 (the method’s return value) on the screen. Math.floor() returns a value that is equal to or less than the argument in the parentheses. It does not round numbers up. If you would like to round off to the nearest integer, use the Math.round() method. If you were to create the following statement

document.write(Math.round(8.93));

you would get 9 as an answer.


Tip

With all math functions, you can use a variable or expression as the function argument.


Math.floor() and Math.round() work for negative arguments as well. The following line of code

document.write(Math.floor(-7.6));

prints -8. This might surprise you until you learn the complete definition of Math.floor(). It returns the highest integer that is less than or equal to the argument in parentheses. The highest integer less than or equal to −7.6 is −8.

You don’t have to be an expert in math to use many of the mathematical functions that come with JavaScript. Often, even in business applications, the following method comes in handy:

Math.abs(numeric value)

The Math.abs() method, called the absolute value method, can be used in many programs as well. Math.abs() returns the absolute value of its argument. The absolute value of a number is simply the positive representation of a positive or negative number. Whatever argument you pass to Math.abs(), its positive value is returned. For example, the line of code

document.write(Math.abs(-5) + " "+ Math.abs(-5.75)+" "+ Mat.bs(0)+" "+Math.
abs(5.7));

produces the following output:

5 5.75 0 5.7

The following advanced math methods are available if you need them:

Math.atn(numeric value);
Math.cos(numeric value);
Math.sin(numeric value);
Math.tan(numeric value);
Math.exp(numeric value);
Math.log(numeric value);

These are probably some of the least-used functions in JavaScript. This is not to belittle the work of scientific and mathematical programmers who need them; thank goodness JavaScript supplies these functions! Otherwise, programmers would have to write their own versions.

The Math.atn() function returns the arctangent of the argument in radians. The argument is assumed to be an expression representing an angle of a right triangle. If you’re familiar with trigonometry (and who isn’t, right?), you may know that the result of all arctangent calculations always falls between -π/2 and /2 and the Math.arc() function requires that its argument also fall within this range. Math.cos() always returns the cosine of the angle of the argument expressed in radians. Math.sin() returns the sine of the angle of the argument expressed in radians. Math.tan() returns the tangent of the angle of the argument expressed in radians.


Tip

If you need to pass an angle expressed in degrees to these functions, convert the angle to radians by multiplying it by (π/180). (π is approximately 3.141592654.)


If you understand these trigonometric functions, you should have no trouble with the Math.exp() and Math.log(). You use them the same way. If you do not understand these mathematical functions, that’s OK. Some people program in JavaScript for years and never need them.

Math.exp() returns the base of natural logarithm (e) raised to a specified power. The argument to Math.exp() can be any constant, variable, or expression less than or equal to 88.02969. e is the mathematical expression for the value 2.718282. The following program shows some Math.exp() statements:

document.write(Math.exp(1));
document.write(Math.exp(2));
document.write(Math.exp(3));
document.write(Math.exp(4));
document.write(Math.exp(5));

Here is the output produced by these five document.write statements:

2.71828183
7.3890561
20.0855369
54.59815
148.413159

Notice the first number; e raised to the first power does indeed equal itself.

Math.log() returns the natural logarithm of the argument. The argument to Math.log() can be any positive constant, variable, or expression. The following program line demonstrates the Math.log() function in use:

document.write(Math.log(3));

Here is the output:

1.098612

Summary

You now understand how JavaScript calculations work. By utilizing the math operators and by understanding the math hierarchy, you will know how to compose your own calculations.

By understanding the ASCII table, you not only better understand how computers represent characters internally, but you also understand how to access those ASCII values by using the String.fromCharCode() method. Many of JavaScript’s methods are universal—similar functions exist in many languages that you’ll learn throughout your programming career.

Q&A

Q. In JavaScript, do I have to know all the values that I will assign to variables when I write the program?

A. Data comes from all sources. You will know some of the values that you can assign when you write your programs, but much of your program data will come from the user or from data files.

Q. What kinds of data can variables hold?

A. Variables can hold many kinds of data, such as numbers, characters, and character strings. As you learn more about programming, you will see that numeric data comes in all formats and, to master a programming language well, you must also master the kinds of numeric data that are available. Some programming languages, such as Visual Basic and C, support variables that hold time and date values as well.

Workshop

The quiz questions and exercises are provided for your further understanding.

Quiz

1. What is the result of the following expression?

(1 + 2) * 4 / 2

2. What is the result of the following expression?

(1 + (10 - (2 + 2)))

3. What is a method?

4. What is the output from the following document.write statement?

document.write(Math.floor(-5.6));

5. What is the output from the following document.write statement?

document.write(Math.pow(3,4));

6. Write a document.write method call that replaces the “Liberty Basic” in “Teach Yourself Liberty Basic” to “JavaScript”.

7. Name the three trigonometric functions mentioned in this hour.

8. What is the difference between Math.round() and Math.floor()?

9. What does the following statement print?

document.write(String.fromCharCode(65,67,69));

Answers

1. 6

2. 7

3. A method is a section of code designed to perform a specific task.

4. -6

5. 81

6.

CompLang = "Teach Yourself Liberty Basic";
document.write(CompLang.replace("Liberty Basic","JavaScript"));

7. The three trigonometric functions are sin(), cos(), and tan().

8. Math.floor() will return the integer value of a number passed to it. Math.round() will return the integer value of the number if the decimal portion is less than .5 or the next highest integer if the decimal portion is .5 or higher.

9. ACE

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

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