1. STRINGS AND NUMBERS
In the last lesson, you learned about getting strings and numbers as user input; however, before moving on to conditions and loops, look a little more closely at using strings and numbers.
A number is either an integer (whole number, no decimal point) or a floating-point number (includes a decimal point and values to the right of the decimal point).
JavaScript allows you to work with values in decimal (base 10), hexadecimal (base 16), and octal (base 8).
The following are a few rules:
- Decimal values can't begin with a leading zero. Your script must strip the leading zeroes from the input string or use a number parsing function, such as parseInt(), before performing any math calculations on the input. (More details on parseInt() are presented later in this lesson).
- Hexadecimal integers begin with a leading 0x or 0X (that's zero, not an O). Hex code for color is a hexadecimal triplet (three hex values), but not all hex values are in this form. For example, 0X2B, 0X1a, 0xcc are all valid hex values.
- Octal values begin with a leading zero followed by any digits between 0 and 7.
Because JavaScript is weakly typed, it's important to understand how JavaScript converts from strings to numbers and vice versa.
2. DATA TYPE CONVERSION
JavaScript is a dynamically typed language. This means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
So, for example, you could define a variable as follows:
var answer = 42
And later, you could assign the same variable a string value, for example:
answer = "Thanks for all the fish . . ."
Because JavaScript is dynamically typed, this doesn't cause an error message.
In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings, as discussed in Lesson 2.
For example, consider the following statements:
x = "The answer is " + 42 // returns "The answer is 42"
JavaScript comments are preceded by //.
In this statement, a string value and a numeric value are concatenated
together -- the numeric value (42) is converted to a string
("42").
In statements involving other operators, JavaScript doesn't convert numeric values to strings. For example:
"37" - 7 // returns 30
however
"37" + 7 // returns 377
Most time, you don't need to be too concerned because JavaScript will figure out from the context of the rest of the code statement what to do with a specific piece of data and whether to treat it as a number or as a string.
The major exception to this is addition. To do a numerical addition, you need to transform your data in some way to make sure that the data is treated as a number and added together, rather than being treated as a string and concatenated.
You can transform your data using the JavaScript's parseInt()
and parseFloat() functions, as well as the other techniques
covered in Lesson 2. In the following section, you look closer at the details
of these useful functions.
3. USING PARSEINT() AND PARSEFLOAT()
The syntax for parseInt() is:
parseInt(string, radix)
The parseInt function parses its first
argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to the
JavaScript interpreter that it needs to convert to a decimal number (base
10); a radix of 8 indicates an octal number (base 8); a radix of 16 denotes a
hexadecimal number (base 16); and so on. For radixes above 10, the letters of
the alphabet indicate numerals greater than 9. For example, for hexadecimal
numbers (base 16), A through F are used.
Parse is a linguistic term that means to break into smaller pieces for analysis.
If parseInt encounters a character that isn't a numeral in the
specified radix, it ignores it and all succeeding characters and returns the
integer value parsed up to that point. The parseInt function
truncates (cuts off) numbers to integer values.
Leading and trailing spaces are allowed.
If the radix isn't specified or is specified as 0, JavaScript assumes the following:
- If the input string begins with "0x", the radix is 16 (hexadecimal).
- If the input string begins with "0", the radix is 8 (octal).
- If the input string begins with any other value, the radix is 10 (decimal).
- If the first character cannot be converted to a number, parseInt returns NaN (not a number).
The parseFloat function is similar to parseInt. parseFloat() parses a string and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), numeral (0-9), decimal point, or exponent, it returns the value up to that point and ignores that character and all succeeding characters. If the first character can't be converted to a number, it returns NaN (not a number).
Unlike parseInt(), parseFloat() doesn't need a
radix value -- it automatically strips leading zeros.
4. TEST AND DEBUG YOUR CODE
Remember to test your code, and if your script includes user input, be sure to test it out with different kinds of data to see how it performs. Depending on the script, you may want to test the following:
- an octal number (such as 0300)
- a floating-point number (such as 1.2)
- text
If you don't understand the results you're getting from your script, try testing it by inserting alert statements to find out the value of a variable at various stages in your script, such as
var myFirstValue = prompt
("Enter a number","");
alert(myFirstValue);
var mySecondValue = prompt
("What's your age?","");
alert(mySecondValue);
You can add as many alerts as you need during testing and then remove them after your script has been tested and debugged.
5. USE FLOW CONTROL
All programming languages include statements that control the flow of the
program under various conditions. The if-else statement is the
one most commonly used, and it works just the way you'd expect: If this
happens, do A, else if that happens, do B.
Conditional operators are used to create conditions in your scripts. JavaScripts's conditional operators are shown in the following table.
| Conditional Operator | Description |
==
|
equality (what's to the left of this operator is exactly the same as what's to the right) |
<
|
less than |
>
|
greater than |
<=
|
less than or equal to |
>=
|
greater than or equal to |
!=
|
not equal to |
The assignment operator (=) is an arithmetic operator. The equality operator (==) is a conditional operator. One of the most common mistakes in beginning JavaScript is to use the assignment operator in a condition rather than the equality operator.
6. IF STATEMENTS
If statements test one or more conditions. The basic syntax is
as follows:
if (condition) {
statement 1
statement 2
. . .
}
If the condition is true, the block of code contained in the curly braces
{} following the condition is executed. If the condition is
false, the first code statement following the closing curly brace is
executed; in other words, the if statement is ignored, and the
parser moves on to the next code statement. The following's an example of an
if statement:
if (myTrash == full)
{
alert ("The Trash can is full!");
alert ("Empty the Trash!);
}
Note that there's no semicolon after the condition or after the closing curly
brace, but there are semicolons after each statement in the code block. Also
notice that the if condition (the part in the parentheses) uses
the equality operator, and the statements in the code block (between the
curly braces) use the assignment operator. If you mistakenly use the
assignment operator in the if condition, such as the following:
if (myTrash = full)
{
alert ("The Trash can is full!");
alert ("Empty the Trash!);
}
in this case, the condition will always be true,
and so the if statement will always be executed.
You don't have to use curly braces if there's only one statement in your code block, for example:
if (myVariable == 5) myOtherVariable = 25;
An if statement can be used alone, or it can be combined with an
else or an else-if statement:
if (myVariable == 5)
{
myVariable = 15;
myOtherVariable = 25;
}
else
{
alert ("myVariable is not equal to 5");
alert ("Choose a new variable.");
}
By using an if/else-if statement, you can include three or more
conditions in your statement, such as the following:
if (myAccountBalance == 0){
myTransfer = 100;
alert ("Funds transferred!");
}
else if (myAccountBalance < 0) {
myTransfer = 200;
alert ("Overdrawn!");
}
else
alert ("Cruising!");
7. LOGICAL OPERATORS
Logical operators can also be used in conditional statements. The logical operators return a Boolean value -- in other words, true or false. The logical operators are shown in the following table.
| Logical Operator | Description |
|
&&
|
AND |
|
||
|
OR |
|
!
|
NOT |
Using logical operators, you can combine conditions in an if
statement; for example:
if (fName == "Fred" && lName == "Astaire") {
tName = fName + " " + lName;
alert("Welcome, " + tName);
}
This if statement tests both the first condition and the second
condition, and executes the code block if both conditions are true.
8. USE WHILE LOOPS
Programming languages also include loops. Loops are used to do an action over
and over again. JavaScript uses both while loops and
for loops.
A while loop works such as the following:
while (condition) statement(s) to execute
As long as the condition is true, the statements will be repeatedly executed. The statement block generally includes a counter that modifies the condition; otherwise, you create an infinite loop. If the condition is never true, the statements are never executed.
The following is an example of a while statement:
var counter = 10;
while (counter > 5)
{
document.write
("The counter is now: " + counter + "<br>");
counter = counter - 1;
}
alert("Finished counting!");
Notice the counter variable before the while loop begins. A
value of 10 is assigned to counter. The code block in the loop (the part
between the curly braces) runs five times until the counter value is equal to
5, and the loop stops.
Also note the "<br>" in the document.write
statement. JavaScript allows you to include HTML code to be output by
scripts. In this case, you're inserting a line break after each instance of
the document.write statement output.
The following statement:
counter = counter - 1;
could also be written such as the following:
counter--;
The -- is called the decrement
operator . There is also an increment operator (++) that adds one to the
value. These two statements are equivalent to the following:
counter = counter + 1; counter++;
9. FOR LOOPS
A for loop includes the following three components:
- initialization
- test condition
- increment/decrement
For example:
for (i=0; i<=10; i++) {
document.write("i = : " + i + "<br>");
}
In this case,
- initalization: i = 0
- test condition: i <= 10
- increment: i++
A while loop is really a reformulation of a for
loop. It includes a test condition and a counter (iterator). The loop
continues as long as the test condition is true.
You can reformulate the previous for loop as a
while loop, as shown in the following code:
i=0;
while (i <= 10){
i++;
document.write("i = : " + i + "<br>");
}
In this case,
- initalization: i = 0 -- this is done before the loop starts
- test condition: i <= 10 -- the loop continues as long as this is true
- increment: i++ -- occurs within the code block of the loop
Moving On
In this lesson, you learned more about using strings and numbers. You also
learned how to create three types of flow control statements
(if, if/else, if/else-if/else). In
addition, you found about while and for loops to
repeat blocks of code as long as certain conditions are met.
In the Lesson 5, you learn add a date and time to your pages automatically, and how to create a timer so that scripts execute only after a certain amount of time has elapsed.
Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to share questions, solutions, and experiences with your fellow students.
