What You’ll Learn in This Lesson:
How to name, declare, and assign variables
How to choose whether to use local or global variables
How to convert between different data types
How to create and use String
objects
How to create and use arrays of numbers and strings
How to define, call, and return values from functions
How to use object properties and values
How to define and use object methods
How to use the Math
object’s methods
How to use new
and this
keywords to work with objects
How to use the Date
object to work with dates
Now that you have learned some of the fundamentals of JavaScript and the DOM, it’s time to dig into more details of the JavaScript language.
In this lesson, you’ll learn three tools for storing data in JavaScript: variables, which store numbers or text; strings, which are special variables for working with text; and arrays, which are multiple variables you can refer to by number. Variables, strings, and arrays are not the most exciting elements of any programming language when described individually, but as you will see throughout the rest of these lessons, variables, strings, and arrays are fundamental to just about every bit of complex JavaScript that you’ll develop.
In this lesson, you’ll also learn about two more key JavaScript concepts that you’ll use throughout the rest of these lessons (and in your future JavaScript endeavors). You’ll learn the details of creating and using functions, which enable you to group any number of statements into a single block. Functions are useful for creating reusable sections of code, and you can create functions that accept parameters and return values for later use.
Whereas functions enable you to group sections of code, objects enable you to group data. You can use objects to combine related data items and functions for working with the data. You’ll learn how to define and use objects and their methods and will work specifically with two of the most useful objects built into JavaScript: Math
and Date
.
Unless you have skipped over all the JavaScript-related lessons so far, you’ve already used a few variables. You probably can also figure out how to use a few more without any additional help. Nevertheless, there are some aspects of variables you haven’t learned yet, and they are covered in the next few sections.
As a reminder, variables are named containers that can store data (for example, a number, a text string, or an object). As you learned earlier, every variable has a unique name of your choosing. However, there are rules you must follow when choosing a variable name:
Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 0–9 and the underscore (_) character.
Variable names cannot include spaces or any other punctuation characters.
The first character of the variable name must be either a letter or an underscore.
Variable names are case sensitive; for example, totalnum
, Totalnum
, and TotalNum
are interpreted as separate variable names.
There is no official limit on the length of a variable name, but it must fit on one line. Frankly, if your variable names are longer than that—or even longer than 25 or so characters, you might consider a different naming convention.
Using these rules, the following are examples of valid variable names:
total_number_of_fish
LastInvoiceNumber
temp1
a
_var39
Note
You can choose to use either friendly, easy-to-read names or completely cryptic ones. Do yourself a favor: Use longer (but not too long), friendly names whenever possible. Although you might remember the difference between a
, b
, x
, and x1
right now, you might not after spending a few days away from the code, and someone who isn’t you most certainly won’t understand your cryptic naming convention without some documentation.
Some computer languages require you to declare a variable before you use it. JavaScript includes the var
keyword, which can be used to declare a variable. In many cases you can omit var
, and the variable is still declared the first time you assign a value to it.
To understand where to declare a variable, you need to understand the concept of scope. A variable’s scope is the area of the script in which that variable can be used. There are two types of variables:
Global variables have the entire script (and other scripts in the same HTML document) as their scope. They can be used anywhere, even within functions.
Local variables have a single function as their scope. They can be used only within the function they are created in.
To create a global variable, you declare it in the main script, outside any functions. You can use the var
keyword to declare the variable, as in this example:
var students = 25;
This statement declares a variable called students
and assigns it the value 25
. If this statement is used outside functions, it creates a global variable. The var
keyword is optional in this case, so this statement is equivalent to the preceding one:
students = 25;
Before you get in the habit of omitting the var
keyword, be sure you understand exactly when it’s required. It’s actually a good idea to always use the var
keyword; if you always use it, you’ll avoid errors and make your script easier to read, and it won’t usually cause any trouble.
A local variable belongs to a particular function. Any variable you declare with the var
keyword in a function is a local variable. In addition, the variables in the function’s parameter list are always local variables.
To create a local variable within a function, you must use the var
keyword. This forces JavaScript to create a local variable, even if there is a global variable with the same name. However, try to keep your variable names distinct, even if you are using them in different scopes.
You should now understand the difference between local and global variables. If you’re still a bit confused, don’t worry: If you use the var
keyword every time, you’ll usually end up with the right type of variable.
As you learned in Lesson 4, “Understanding JavaScript,” you use the equal sign (=
) to assign a value to a variable. For example, this statement assigns the value 40
to the variable lines
:
var lines = 40;
You can use any expression to the right of the equal sign, including other variables. For example, earlier you used this syntax to add 1 to a variable:
lines = lines + 1;
Because incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. The first is the +=
operator, which enables you to create the following shorter version of the preceding example:
lines += 1;
Similarly, you can subtract a number from a variable by using the −
=
operator:
lines −= 1;
If you still think that’s too much to type, JavaScript also includes the increment and decrement operators, ++
and −−
. This statement adds 1 to the value of lines
:
lines++;
Similarly, this statement subtracts 1 from the value of lines
:
lines−−;
You can alternatively use the ++
or −−
operators before a variable name, as in ++lines
. However, ++lines
and lines++
are not identical. The difference is in when the increment or decrement happens:
If the operator is after the variable name (for example, lines++
), the increment or decrement happens after the current expression is evaluated.
If the operator is before the variable name (for example, ++lines
), the increment or decrement happens before the current expression is evaluated.
This difference is an issue only when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines
variable the value 40
. The following two statements have different effects:
alert(lines++);
alert(++lines);
The first statement displays an alert with the value 40
and then increments lines
to 41
. The second statement first increments lines
to 41
and then displays an alert with the value 41
.
Note
The increment and decrement operators are strictly for your convenience. If it makes more sense to you to stick to lines = lines + 1
, do it; your script won’t suffer.
An expression is a combination of variables and values that the JavaScript interpreter can evaluate to a single value, such as 2
+
2 = 4
. The characters that are used to combine these values, such as +
and /
, are called operators.
Note
Along with variables and constant values, expressions can also include function calls that return results.
In the basic JavaScript examples so far in these lessons, you’ve already used some operators, such as the +
sign (addition) and the increment
and decrement
operators. Table 22.1 lists some of the most important (and common) operators used in JavaScript expressions.
Operator |
Description |
Example |
|
Concatenate (combine) strings |
|
|
Add |
|
|
Subtract |
|
|
Multiply |
|
|
Divide |
|
|
Modulo (remainder) |
|
|
Increment |
|
|
Decrement |
|
Along with these, there are also many other operators used in conditional statements. You’ll learn about them in Lesson 23, “Controlling Flow with Conditions and Loops.”
When you use more than one operator in an expression, JavaScript uses rules of operator precedence to decide how to calculate the value. Table 22.1 lists the operators from lowest to highest precedence, and operators with highest precedence are evaluated first. For example, consider this statement:
result = 4 + 5 * 3;
If you try to calculate this result, there are two ways to do it. You could multiply 5 * 3
first and then add 4
(result: 19
), or you could add 4 + 5
first and then multiply by 3
(result: 27
). JavaScript solves this dilemma by following the precedence rules: Because multiplication has a higher precedence than addition, JavaScript first multiplies 5 * 3
and then adds 4
, producing a result of 19
. Sometimes operator precedence doesn’t produce the result you want. For example, consider this statement:
result = a + b + c + d / 4;
This is an attempt to average four numbers by adding them all together and then dividing by four. However, because JavaScript gives division a higher precedence than addition, it will divide the d
variable by 4
before adding the other numbers, producing an incorrect result.
You can control precedence by using parentheses. Here’s the working statement to calculate an average:
result = (a + b + c + d) / 4;
The parentheses ensure that the four variables are added first, and then the sum is divided by four. If you’re unsure about operator precedence, you can use parentheses to make sure things work the way you expect and to make your script more readable.
In some computer languages, you have to specify the type of data a variable will store (for example, a number or a string). In JavaScript, you don’t need to specify a data type in most cases. However, you should know the types of data JavaScript can deal with.
These are the basic JavaScript data types:
Number—Examples of numbers are 3
, 25
, and 1.4142138
. JavaScript supports both integers and floating-point numbers.
Boolean—Booleans are logical values. A Boolean can have one of two values, true
or false
, and is useful for indicating whether a certain condition is true.
String—A string, such as "I am a jelly doughnut"
, consists of one or more characters of text. (Strictly speaking, strings are String
objects, which you’ll learn about later in this lesson.)
Null—The null value, represented by the keyword null
, is the value of an undefined variable. For example, the statement document.write(fig)
will result in a null value (and an error message) if the variable fig
has not been previously used or defined.
Although JavaScript keeps track of the data type currently stored in each variable, it doesn’t restrict you from changing types midstream. For example, suppose you declare a variable by assigning it a value, like so:
var total = 31;
This statement declares a variable called total
and assigns it the value 31
. This is a numeric variable. Now suppose you change the value of total
:
total = "albatross";
This assigns a string value to total
, replacing the numeric value. JavaScript will not display an error when this statement executes; it’s perfectly valid, although it’s probably not a very useful “total.”
Note
Although this feature of JavaScript is convenient and powerful, it can also make it easy to make a mistake. For example, if the total
variable is later used in a mathematical calculation, the result would be invalid—but JavaScript does not warn you that you’ve made this mistake.
JavaScript handles conversions between data types for you whenever it can. For example, you’ve already used statements like this:
document.write("The total is " + total);
This statement prints out the message "The total is 40"
. Because the document.write
function works with strings, the JavaScript interpreter automatically converts any nonstrings in the expression (in this case, the value of total
) to strings before performing the function.
This works equally well with floating-point and Boolean values. However, there are some situations in which it won’t work. For example, the following statement will work fine if the value of total
is 40
:
average = total / 3;
However, the total
variable could also contain a string; in this case, the preceding statement would result in an error.
In some situations, you might end up with a string containing a number and need to convert it to a regular numeric variable. JavaScript includes two functions for this purpose:
parseInt—Converts a string to an integer number
parseFloat—Converts a string to a floating-point number
Both of these functions will read a number from the beginning of the string and return a numeric version. For example, these statements convert the string "30 angry polar bears"
to a number:
var stringvar = "30 angry polar bears";
var numvar = parseInt(stringvar);
After these statements execute, the numvar
variable contains the number 30
; the nonnumeric portion of the string is ignored.
Note
These functions look for a number of the appropriate type at the beginning of the string. If a valid number is not found, the function returns the special value NaN
, meaning not a number.
String
ObjectsYou’ve already used several strings in the brief JavaScript examples found in previous lessons. Strings store a group of text characters and are named similarly to other variables. As a simple example, this statement assigns the string This is a test
to a string variable called stringtest
:
var stringtest = "This is a test";
In the following sections, you’ll learn a little more about the String
object and see it in action in a full script.
String
ObjectJavaScript stores strings as String
objects. You usually don’t need to worry about this piece of information—that your strings are in fact objects—but it will explain some of the common techniques you’ll see for working with strings, which use methods (built-in functions) of the String
object.
There are two ways to create a new String
object. The first is the one you’ve already used, and the second way involves using object-oriented syntax. The following two statements create the same string:
var stringtest = "This is a test";
stringtest = new String("This is a test");
The second statement uses the new
keyword, which you use to create objects. This tells the browser to create a new String
object containing the text This is a test
and assigns it to the variable stringtest
.
Note
Although you can create a string by using object-oriented syntax, the standard JavaScript syntax is simpler, and there is no difference in the strings created by these two methods.
You can assign a value to a string in the same way as any other variable. Both of the examples in the preceding section assigned an initial value to the string. You can also assign a value after the string has already been created. For example, the following statement replaces the contents of the stringtest
variable with a new string:
var stringtest = "This is only a test.";
You can also use the concatenation operator (+
) to combine the values of two strings. Listing 22.1 shows a simple example of assigning and combining the values of strings.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>String Text</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>String Test</h1>
<script>
var stringtest1 = "This is a test. ";
var stringtest2 = "This is only a test.";
var bothstrings = stringtest1 + stringtest2;
alert(bothstrings);
</script>
</body>
</html>
This script assigns values to two string variables, stringtest1
and stringtest2
, and then displays an alert with their combined value (the variable bothstrings
). If you load this HTML document in a browser, your output should resemble what’s shown in Figure 22.1.
In addition to using the +
operator to concatenate two strings, you can use the +=
operator to add text to a string. For example, this statement adds a period to the current contents of a string variable named sentence
:
sentence += ".";
Note
The plus sign (+
) is also used to add numbers in JavaScript. The browser knows whether to use addition or concatenation based on the type or types of data you use with the plus sign. If you use it between a number and a string, the number is converted to a string and concatenated.
From time to time, you might find it useful to know how many characters a string variable contains. You can do this with the length
property of String
objects, which you can use with any string. To use this property, type the string’s name followed by .length
.
For example, stringtest.length
refers to the length of the stringtest
string. Here is an example of this property:
var stringtest = "This is a test.";
document.write(stringtest.length);
The first statement assigns the string This is a test.
to the stringtest
variable. The second statement displays the length of the string—in this case, 15 characters. The length
property is a read-only property, so you cannot assign a value to it to change a string’s length.
Note
Remember that although stringtest
refers to a string variable, the value of stringtest.length
is a number and can be used in any numeric expression.
Two methods of the String
object enable you to convert the contents of a string to all uppercase or all lowercase:
toUpperCase—Converts all characters in the string to uppercase
toLowerCase—Converts all characters in the string to lowercase
For example, the following statement displays the value of the stringtest
string variable in lowercase:
document.write(stringtest.toLowerCase());
If this variable contained the text This Is A Test
, the result would be the following string:
this is a test
Note that the statement doesn’t change the value of the stringtest
variable. These methods return the upper- or lowercase version of the string, but they don’t change the string itself. If you want to change the string’s value, you can use a statement like this:
stringtest = stringtest.toLowerCase();
Note
Note that the syntax for these methods is similar to the syntax for the length
property introduced earlier. The difference is that methods always use parentheses, whereas properties don’t. The toUpperCase
and toLowerCase
methods do not take any parameters, but you still need to use the parentheses.
In the short examples so far in this lesson, you’ve worked only with entire strings. Like most other programming languages, JavaScript also enables you to work with substrings, or portions of a string. You can use the substring
method to retrieve a portion of a string or the charAt
method to get a single character. These are explained in the following sections.
The substring
method returns a string consisting of a portion of the original string between two index values, which you must specify in parentheses. For example, the following statement displays the fourth through sixth characters of the stringtest
string:
document.write(stringtest.substring(3,6));
At this point, you’re probably wondering where the 3
and the 6
come from. There are three things you need to understand about using index parameters, regardless of when you’re using them:
Indexing starts with 0
for the first character of the string, so the fourth character is actually index 3
.
The second index is noninclusive. A second index of 6
includes up to index 5
(the sixth character).
You can specify the two indexes in either order. The smaller one will be assumed to be the first index. In the previous example, (6,3)
would produce the same result. Of course, there is rarely a reason to use the reverse order.
As another example, suppose you define a string called alpha
to hold an uppercase version of the alphabet:
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
The following are examples of the substring
method using the alpha
string:
alpha.substring(0,4)
returns ABCD
.
alpha.substring(10,12)
returns KL
.
alpha.substring(12,10)
also returns KL
. Because 10
is the smaller of the two values, it is used as the first index.
alpha.substring(6,7)
returns G
.
alpha.substring(24,26)
returns YZ
.
alpha.substring(0,26)
returns the entire alphabet.
alpha.substring(6,6)
returns the null
value, an empty string. This is true whenever the two index values are the same.
Using the charAt
method is a simple way to grab a single character from a specified position within a string. To use this method, specify the character’s index, or position, in parentheses. As you’ve learned, the index begins at 0
for the first character. Here are a few examples of using the charAt
method on the alpha
string:
alpha.charAt(0)
returns A
.
alpha.charAt(12)
returns M
.
alpha.charAt(25)
returns Z
.
alpha.charAt(27)
returns an empty string because there is no character at that position.
Another use for substrings is to find a string within another string. One way to do this is with the indexOf
method. To use this method, add indexOf
to the string you want to search and specify the string to search for in the parentheses. This example searches for this
in the stringtest
string and assigns the result to a variable called location
:
var location = stringtest.indexOf("this");
Caution
As with most other JavaScript methods and property names, indexOf
is case sensitive. Make sure you type it exactly as shown here when you use it in scripts.
The value returned in the location
variable is an index into the string, similar to the first index in the substring
method. The first character of the string is index 0
.
You can specify an optional second parameter in this method to indicate the index value to begin the search. For example, this statement searches for the word fish
in the moretext
string, starting with the 20th character:
var newlocation = moretext.indexOf("fish",19);
Note
One use for the second parameter of this method is to search for multiple occurrences of a string. After finding the first occurrence, you search starting with that location for the second one, and so on.
A second method, lastIndexOf
, works the same way but finds the last occurrence of the string. It searches the string backward, starting with the last character. For example, this statement finds the last occurrence of Fred
in the names
string:
var namelocation = names.lastIndexOf("Fred");
As with indexOf
, you can specify a location to search from as the second parameter. In this case, the string will be searched backward, starting at that location.
An array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores
to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array.
Unlike with most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements:
scores = new Array(4);
To assign a value to the array, you use an index in brackets. As you’ve seen earlier in this lesson, an index begins with 0
, so the elements of the array in this example would be numbered 0
to 3
. These statements assign values to the four elements of the array:
scores[0] = 39;
scores[1] = 40;
scores[2] = 100;
scores[3] = 49;
You can also declare an array and specify values for elements at the same time. This statement creates the same scores
array in a single line:
scores = new Array(39,40,100,49);
You can also use a shorthand syntax to declare an array and specify its contents. Using the following statement is an alternative way to create the scores
array:
scores = [39,40,100,49];
Caution
Remember to use parentheses when declaring an array with the new
keyword, as in a = new Array(3,4,5)
, and use brackets when declaring an array without new
, as in a = [3,4,5]
. Otherwise, you’ll run into JavaScript errors.
Like strings, arrays have a length
property. This property tells the number of elements in the array. If you specified the length when creating the array, this value becomes the length
property’s value. For example, these statements would print the number 30
:
scores = new Array(30);
document.write(scores.length);
You can declare an array without a specific length and change the length later by assigning values to elements or changing the length
property. For example, these statements create a new array and assign values to two of its elements:
test = new Array();
test[0]=21;
test[5]=22;
In this example, because the largest index number assigned so far is 5
, the array has a length
property of 6
. Remember that elements are numbered starting at 0
.
You can read the contents of an array by using the same notation you used when assigning values. For example, the following statements would display the values of the first three elements of the scores
array:
scoredisplay = "Scores: " + scores[0] + "," +
scores[1] +
"," + scores[2];
document.write(scoredisplay);
Note
Looking at this example, you might imagine it would be inconvenient to display all the elements of a large array. This is an ideal job for loops, which enable you to perform the same statements several times with different values. You’ll learn all about loops in Lesson 23.
So far, you’ve used arrays of numbers. JavaScript also enables you to use string arrays, or arrays of strings. This is a powerful feature that enables you to work with a large number of strings at the same time.
You declare a string array in the same way as a numeric array—in fact, JavaScript does not make a distinction between them:
names = new Array(30);
You can then assign string values to the array elements:
names[0] = "John H. Watson";
names[1] = "Sherlock Holmes";
As with numeric arrays, you can also specify a string array’s contents when you create it. Either of the following statements would create the same string array as the preceding example:
names = new Array("John H. Watson", "Sherlock Holmes");
names = ["John H. Watson", "Sherlock Holmes"];
You can use string array elements anywhere you would use a string. You can even use the string methods introduced earlier. For example, the following statement prints the first four characters of the first element of the names
array, resulting in John
:
document.write(names[0].substring(0,4));
JavaScript includes a string method called split
, which splits a string into its component parts. To use this method, specify the string to split and a character to divide the parts:
name = "John Q. Public";
parts = name.split(" ");
In this example, the name
string contains the name John Q. Public
. The split
method in the second statement splits the name
string at each space, resulting in three strings. These are stored in a string array called parts
. After the sample statements execute, the elements of parts
contain the following:
parts[0] = "John"
parts[1] = "Q."
parts[2] = "Public"
JavaScript also includes an array method, join
, that performs the opposite function. This statement reassembles the parts
array into a string:
fullname = parts.join(" ");
The value in the parentheses specifies a character to separate the parts of the array. In this case, a space is used, resulting in the final string John Q. Public
. If you do not specify a character, commas are used.
JavaScript also includes a sort
method for arrays, which returns an alphabetically sorted version of the array. For example, the following statements initialize an array of four names and sort it:
names[0] = "Public, John Q.";
names[1] = "Doe, Jane";
names[2] = "Duck, Daisy";
names[3] = "Mouse, Mickey";
sortednames = names.sort();
The last statement sorts the names
array and stores the result in a new array, sortednames
.
Because the sort
method sorts alphabetically, it won’t work with a numeric array—at least not the way you’d expect. If an array contains the numbers 4, 10, 30, and 200, for example, it would sort them as 10, 200, 30, 4—not even close. Fortunately, there’s a solution: You can specify a function in the sort
method’s parameters, and that function is used to compare the numbers. The following code sorts a numeric array correctly:
function numbercompare(a,b) {
return a−b;
}
numbers = new Array(30, 10, 200, 4);
sortednumbers = numbers.sort(numbercompare);
This example defines a simple function, numbercompare
, that subtracts the two numbers. After you specify this function in the sort
method, the array is sorted in the correct numeric order: 4, 10, 30, 200.
Note
JavaScript expects the comparison function to return a negative number if a
belongs before b
, 0
if they are the same, or a positive number if a
belongs after b
. This is why a
−
b
is all you need for the function to sort numerically.
To gain more experience working with JavaScript’s string and array features, you can create a script that enables the user to enter a list of names and displays the list in sorted form. Because this will be a larger script, you should create separate HTML and JavaScript files, as described in Lesson 20, “Getting Started with JavaScript Programming.” First, the sort.html
file will contain the HTML structure and form fields for the script to work with. Listing 22.2 shows the HTML document.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Array Sorting Example</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
textarea.</p>
<form name="theform">
Name:
<input name="newname"size="20">
<input type="button"name="addname"value="Add"
onclick="SortNames();">
<br>
<h2>Sorted Names</h2>
<textarea cols="60"rows="10"name="sorted">
The sorted names will appear here.
</textarea>
</form>
<script src="sort.js"></script>
</body>
</html>
Because the script is in a separate document, the <script>
tag in this document uses the src
attribute to include a JavaScript file called sort.js
. This document defines a form named theform
, a text field named newname
, an addname
button, and a <textarea>
named sorted
. Your script will use these form fields as its user interface.
Listing 22.3 provides the JavaScript necessary for the sorting process.
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform.newname.value;
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
// Sort the array
names.sort();
document.theform.sorted.value=names.join("
");
}
The script begins by defining two variables with the var
keyword: numbernames
is a counter that increments as each name is added, and the names
array stores the names.
When you type a name into the text field and click the button, the onclick
event handler calls the SortNames
function. This function stores the text field value in a variable, thename
, and then adds the name to the names
array, using numbernames
as the index. It then increments numbernames
to prepare for the next name.
The final section of the script sorts the names and displays them. First, the sort
method is used to sort the names
array. Next, the join
method is used to combine the names, separating them with line breaks, and display them in the <textarea>
.
To test the script, save it as sort.js
and then load the sort.html
file you created previously into a browser. You can then add some names and test the script. Figure 22.2 shows the result after several names have been sorted.
The scripts you’ve seen so far have been simple lists of instructions. The browser begins with the first statement after the <script>
tag and follows each instruction, in order, until it reaches the closing </script>
tag (or encounters an error).
Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To make it easier for you to organize your scripts, JavaScript supports functions, which you learned about briefly in Lesson 20. In this section, you will learn how to define and use functions.
A function is a group of JavaScript statements that can be treated as a single unit. To use a function, you must first define it. Here is a simple example of a function definition:
function Greet() {
alert("Greetings!");
}
This snippet defines a function that displays an alert message to the user. It begins with the function
keyword followed by the name you’re giving to the function—in this case, the function’s name is Greet
. Notice the parentheses after the function’s name. As you’ll learn in short order, the parentheses are not always empty, as they are here.
The first and last lines of the function definition include curly braces ({}
). You use these curly braces to enclose all the statements within the function. The browser uses the curly braces to determine where the function begins and ends.
Between the braces is the core JavaScript code of the function. This particular function contains a single line that invokes the alert
method, which displays an alert message to the user. The message contains the text "Greetings!"
.
Caution
Function names are case sensitive. If you define a function such as Greet
with a capital letter, be sure you use the identical name when you call the function. If you define the function with the name Greet
but you attempt to call the function using greet
, it will not work.
Now, about those parentheses. The current version of the Greet
function always does the same thing: Each time you use it, it displays the same message in the alert pop-up window.
To make this function more flexible, you can add parameters, also known as arguments. These are variables that are received by the function each time it is called. For example, you can add a parameter called who
that tells the function the name of the person to greet, based on the value of that parameter when the function is called. Here is the modified Greet
function:
function Greet(who) {
alert("Greetings, " + who + "!");
}
Of course, to actually call this function and see its behavior in action, you need to include it in an HTML document. It used to be common to include all functions in the <head>
of the document, but best practices now recommend that you include them at the end of the HTML unless there is some specific reason they need to be positioned higher in the document.
Listing 22.4 shows the Greet
function embedded in the header section of an HTML document but not yet called into action.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<p>This is the body of the page.</p>
<script>
function Greet(who) {
alert("Greetings, " + who + "!");
}
</script>
</body>
</html>
You have defined a function and placed it in an HTML document. However, if you load Listing 22.4 into a browser, you’ll notice that it does absolutely nothing besides display the text “This is the body of the page.” This lack of action is because the function is defined—ready to be used—but you haven’t used it yet.
Making use of a function is referred to as calling the function. To call a function, use the function’s name as a statement in a script or as an action associated with an event. To call a function, you need to include the parentheses and the values for the function’s parameters, if any. For example, here’s a statement that calls the Greet
function:
Greet("Fred");
This tells the JavaScript interpreter to go ahead and start processing the first statement in the Greet
function. When you call the function in this manner, with a parameter within the parentheses, you pass the parameter "Fred"
to the function. This value of "Fred"
is then assigned to the who
variable inside the function.
Note
A function can have more than one parameter. To define a function with multiple parameters, list a variable name for each parameter, separating the parameters with commas. To call the function, specify values for the parameters, separated by commas.
Listing 22.5 shows a complete HTML document that includes the function definition and a few buttons within the page that call the function as an action associated with an event. To demonstrate the usefulness of functions, we’ll call it twice to greet two different people—using two different parameters.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Function Example</h1>
<p>Who are you?</p>
<button type="button"onclick="Greet('Fred');">I am Fred</button>
<button type="button"onclick="Greet('Ethel');">I am Ethel</button>
<script>
function Greet(who) {
alert("Greetings, " + who + "!");
}
</script>
</body>
</html>
This listing includes two buttons, each of which calls the Greet
function a bit differently—with a different parameter associated with the call from each button.
Now that you have a script that actually does something, try loading it into a browser. If you click one of the buttons, you should see something like the screen in Figure 22.3, which shows the alert that appears when one of the buttons (I Am Ethel, in this case) is clicked.
The function you created in the preceding example displays a message to the user in an alert pop-up, but a function can also return a value to the script that called it. This means you can use functions to calculate values. As an example, let’s create a function that averages four numbers.
As usual, your function should begin with the function
keyword, the function’s name, and the parameters it accepts. Here we will use the variable names a
, b
, c
, and d
for the four numbers to average. Here is the first line of the function:
function Average(a,b,c,d) {
Note
Here we include the opening brace ({
) on the first line of the function. This is a common style, but you can also place the brace on the next line or on a line by itself.
Next, the function needs to calculate the average of the four parameters. You can calculate this by adding them and then dividing by the number of parameters (in this case, 4). Thus, here is the next line of the function:
var result = (a + b + c + d) / 4;
This statement creates a variable called result
and calculates the value assigned to result
by adding the four numbers and then dividing by 4. (The parentheses are necessary to tell JavaScript to be absolutely sure to perform the addition before the division.)
To send this result back to the script that called the function, you use the return
keyword. Here is the last part of the function:
return result;
}
Listing 22.6 shows the complete Average
function in an HTML document. This HTML document also includes a small script in the <body>
section that calls the Average
function and displays the result.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Function Example: Average</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
<script>
function Average(a,b,c,d) {
var result = (a + b + c + d) / 4;
return result;
}
</script>
</head>
<body>
<h1>Function Example: Average</h1>
<p>The following is the result of the function call.</p>
<p>
<script>
var score = Average(3,4,5,6);
document.write("The average is: " + score);
</script>
</p>
</body>
</html>
The script in Listing 22.6 is an example of a script that won’t work if the function is not loaded in the <head>
of the document. This script is not unobtrusive, as you’ve learned in previous lessons, but making it unobtrusive would require more advanced JavaScript.
If you open the script in Listing 22.6 in your web browser, you will see the average printed on the screen, courtesy of the document.write
method, as shown in Figure 22.4.
You can use a variable with the function call, as shown in Listing 22.6. This statement averages the numbers 3, 4, 5, and 6 and stores the result in a variable called score
:
var score = Average(3,4,5,6);
Note
You can also use the function call directly in an expression. For example, you could use the alert
statement to display the result of the function alert(Average(1,2,3,4))
.
Earlier in this lesson, you learned how to use variables to represent different kinds of data in JavaScript. JavaScript also supports objects, a more complex kind of variable that can store multiple data items and functions. Although a variable can have only one value at a time, an object can contain multiple values, which enables you to group related data items into a single object.
In this lesson, you’ll learn how to define and use your own objects. You’ve already worked with some of them, including the following:
DOM objects—These objects enable your scripts to interact with elements of the web browser and web documents. You learned about these in Lesson 21, “Working with the Document Object Model (DOM).”
Built-in objects—These include strings and arrays, which you learned about previously in this lesson.
The syntax for working with all three types of objects—DOM objects, built-in objects, and custom objects—is the same, so even if you don’t end up creating your own objects, you should have a good understanding of JavaScript’s object terminology and syntax.
When you create an array, you use the following JavaScript statement:
scores = new Array(4);
The new
keyword tells the JavaScript interpreter to use built-in functionality to create an object of the Array
type. Objects have one or more properties—essentially, properties are variables, with values, that are stored within the object. For example, in Lesson 21, you learned you can use the location.href
property to get the URL of the current document because the value (the URL) is assigned to that property, just as a value is assigned to a variable. The href
property is one of the properties of the location
object in the DOM.
You’ve also used the length
property of String
objects, as in the following example:
var stringtest = "This is a test.";
document.write(stringtest.length);
To reiterate, as with variables, each object property has a value. To read a property’s value, you simply reference the object name and property name, separated by a period, in any expression. For instance, the example you just saw uses stringtest.length
. You can change a property’s value by using the =
operator, just as you can change the assignment of a value to a variable. The following example sends the browser to a new URL by assigning a new variable to the location.href
property:
location.href="http://www.google.com/";
Note
An object can also be a property of another object. This is referred to as a child object.
Along with properties, each object can have one or more methods. These are functions that work with an object’s data. For example, as you learned in Lesson 21, the following JavaScript statement reloads the current document:
location.reload();
When you use the reload
method, you’re using a method of the location
object. Like other functions, methods can accept arguments in parentheses, and they can return values. Each object type in JavaScript has its own list of built-in methods. For example, a list of built-in methods for the Array
object can be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods.
Although JavaScript’s variables and arrays provide versatile ways to store data, sometimes you need a more complicated structure, which is when objects are useful. For example, suppose you are creating a script to work with a business card database that contains names, addresses, and phone numbers for various people.
If you were using regular variables, you would need several separate variables for each person in the database: a name variable, an address variable, and so on. This would be very confusing, not to mention quite lengthy to define.
Arrays would improve things—but only slightly. You could have a names array, an addresses array, and a phone number array. Each person in the database would have an entry in each array. This would be more convenient than having many individually named variables, but it is still not perfect.
With objects, you can make the variables that store the database as logical as the physical business cards they are supposed to represent. Each person could be represented by a new Card
object, which would contain properties for name, address, and phone number. You can even add methods to the object to display or work with the information, which is where the real power of using objects comes into play.
In the following sections, you’ll use JavaScript to create a Card
object and some properties and methods. Later in this lesson, you’ll use the Card
object in a script that will be used to display information for several members of this datastore you’ve created through the use of objects.
The first step in creating an object is to name it and its properties. In this case, you should call your object Card
, and it will have the following properties:
name
email
address
phone
To use this object in a JavaScript program, you need to create a function to make new instances of the Card
object. This function is called the constructor for an object. Here is the constructor function for the Card
object:
function Card(name,email,address,phone) {
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
}
The constructor is a simple function that accepts parameters to initialize a new object and assigns them to the corresponding properties. You can think of it like setting up a template for the object. The Card
function in particular accepts several parameters from any statement that calls the function and then assigns these parameters as properties of an object. Because the function is called Card
, the object created is a Card
object.
Notice the this
keyword. You’ll use it anytime you create an object definition. Use this
to refer to the current object—the one that is being created by the function.
Next, you need to create a method to work with the Card
object. Because all Card
objects will have the same properties, it might be handy to have a function that prints the properties in a neat format. You can call this function printCard
.
Your printCard
function will be used as a method for Card
objects, so you don’t need to ask for parameters. Instead, you can use the this
keyword again to refer to the current object’s properties. Here is a function definition for the printCard
function:
function printCard() {
var name_line = "Name: " + this.name + "<br>
";
var email_line = "Email: " + this.email + "<br>
";
var address_line = "Address: " + this.address + "<br>
";
var phone_line = "Phone: " + this.phone + "<hr>
";
document.write(name_line, email_line, address_line, phone_line);
}
This function simply reads the properties from the current object (this
), prints each one with a label string before it, and then creates a new line.
You now have a function that prints a card, but it isn’t officially a method of the Card
object. The last thing you need to do is make printCard
part of the function definition for Card
objects. Here is the modified function definition:
function Card(name,email,address,phone) {
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
this.printCard = printCard;
}
The added statement looks just like another property definition, but it refers to the printCard
function. This new method will work as long as printCard
has its own function definition elsewhere in the script. (A method is essentially a property that defines a function rather than a simple value.)
Note
The previous example uses lowercase names such as address
for properties and a mixed-case name (printCard
) for the method. You can use any case for property and method names, but following the convention shown here is one way to make it clear that printCard
is a method rather than an ordinary property.
Now you can use the object definition and method you just created. To use an object definition, you use the new
keyword to create a new object. This is the same keyword you’ve already used to create Date
and Array
objects. The following statement creates a new Card
object called tom
:
tom = new Card("Tom Jones", "[email protected]",
"123 Elm Street, Sometown ST 77777",
"555-555-9876");
As you can see, creating an object is easy. All you do is call the Card
function (the object definition) and enter the required attributes in the same order that you defined originally (in this case, the parameters name
, email
, address
, phone
).
After this statement executes, you will have a new object to hold Tom’s information. This new object, now named tom
, is called an instance of the Card
object. Just as there can be several string variables in a program, there can be several instances of an object you define.
Rather than specify all the information for a card with the new
keyword, you can assign the properties after the fact. For example, the following script creates an empty Card
object called holmes
and then assigns its properties:
holmes = new Card();
holmes.name = "Sherlock Holmes";
holmes.email = "[email protected]";
holmes.address = "221B Baker Street";
holmes.phone = "555-555-3456";
After you’ve created an instance of the Card
object, using either of these methods, you can use the printCard
method to display its information. For example, this statement displays the properties of the tom
card:
tom.printCard();
Now you’ve created a new object to store business cards and a method to print them. As a final demonstration of objects, properties, functions, and methods, you will now use this object in a web page to display data for several cards.
Your script needs to include the function definition for printCard
, along with the function definition for the Card
object. You will then create three cards and print them in the body of the document. You will use separate HTML and JavaScript files for this example. Listing 22.7 shows the complete script.
// define the functions
function printCard() {
var name_line = "<strong>Name: </strong>" + this.name + "<br>
";
var email_line = "<strong>Email: </strong>" + this.email + "<br>
";
var address_line = "<strong>Address: </strong>" + this.address + "<br>
";
var phone_line = "<strong>Phone: </strong>" + this.phone + "<hr>
";
document.write(name_line, email_line, address_line, phone_line);
}
function Card(name,email,address,phone) {
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
this.printCard = printCard;
}
// Create the objects
var sue = new Card("Sue Suthers",
"[email protected]",
"123 Elm Street, Yourtown ST 99999",
"555-555-9876");
var fred = new Card("Fred Fanboy",
"[email protected]",
"233 Oak Lane, Sometown ST 99399",
"555-555-4444");
var jimbo = new Card("Jimbo Jones",
"[email protected]",
"233 Walnut Circle, Anotherville ST 88999",
"555-555-1344");
// Now print them
sue.printCard();
fred.printCard();
jimbo.printCard();
Notice that the printCard
function has been modified slightly to make things look good, with the labels in boldface. To prepare to use this script, save it as cards.js
. Next, you’ll need to include the cards.js
script in a simple HTML document. Listing 22.8 shows the HTML document for this example.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Business Cards</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>JavaScript Business Cards</h1>
<p>External script output coming up...</p>
<script src="cards.js"></script>
<p>External script output has ended.</p>
</body>
</html>
To test the complete script, save this HTML document in the same directory as the cards.js
file you created earlier and then load the HTML document into a browser. Figure 22.5 shows how this example looks in a browser.
JavaScript includes a feature that enables you to extend the definitions of built-in objects. For example, if you think the String
object doesn’t quite fit your needs, you can extend it by adding a new property or method. This might be very useful, for example, if you want to create a large script that uses many strings and manipulates those strings in unique ways.
You can add both properties and methods to an existing object by using the prototype
keyword. (A prototype is another name for an object’s definition, or constructor function.) The prototype
keyword enables you to change the definition of an object outside its constructor function.
As an example, you can add a method to the String
object definition. You will create a method called heading
, which converts a string into an HTML heading. The following statement defines a string called myTitle
:
var myTitle = "Fred's Home Page";
This statement would output the contents of the myTitle
string as an HTML level 1 heading (<h1>
):
document.write(myTitle.heading(1));
Listing 22.9 adds a heading
method to the String
object definition that will display the string as a heading and then displays three headings using the new method.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test of Heading Method</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<script>
function addHeading(level) {
var html = "h" + level;
var text = this.toString();
var opentag = "<" + html + ">";
var closetag = "</" + html + ">";
return opentag + text + closetag;
}
String.prototype.heading = addHeading;
document.write("This is a heading 1".heading(1));
document.write("This is a heading 2".heading(2));
document.write("This is a heading 3".heading(3));
</script>
</body>
</html>
Caution
The code in Listing 22.9 is not unobtrusive, nor is it particularly accessible. You should use it as an example of how the heading
method works, but it’s not a good idea to use this script in live content.
You need to define the addHeading
function, which will serve as the new string method. It accepts a number to specify the heading level. The opentag
and closetag
variables are used to store the HTML “begin heading tag” and “end heading tag” tags, such as <h1>
and </h1>
.
After the function is defined, use the prototype
keyword to add it as a method of the String
object. You can then use this method on any String
object or, in fact, any JavaScript string. This is demonstrated by the last three statements, which display quoted text strings as level 1, 2, and 3 headings.
If you load this document into a browser, it should look something like what’s shown in Figure 22.6.
Math
ObjectThe Math
object is a built-in JavaScript object that includes math constants and functions. You’ll never need to create a Math
object because it exists automatically in any JavaScript program. The Math
object’s properties represent mathematical constants, and its methods are mathematical functions. If you’re working with numbers in any way in your JavaScript, the Math
object will be your new best friend.
Three of the most useful methods of the Math
object enable you to round decimal values up and down:
Math.ceil—Rounds a number up to the next integer
Math.floor—Rounds a number down to the next integer
Math.round—Rounds a number to the nearest integer
All these methods take the number to be rounded as their only parameter. You might notice one thing missing: the capability to round to a decimal place, such as for dollar amounts. Fortunately, you can easily simulate this, as shown in this simple function that rounds numbers to two decimal places:
function round(num) {
return Math.round(num * 100) / 100;
}
The function shown here multiplies the value by 100 to move the decimal and then rounds the number to the nearest integer. Finally, the value is divided by 100 to restore the decimal to its original position.
One of the most commonly used methods of the Math
object is the Math.random
method, which generates a random number. This method doesn’t require any parameters. The number it returns is a random decimal number between zero and one.
You’ll usually want a random number between one and some predetermined value. You can generate such a number by using a general-purpose random number function. The following function generates random numbers between one and the parameter you send it:
function rand(num) {
return Math.floor(Math.random() * num) + 1;
}
This function multiplies a random number by the value specified in the num
parameter and then converts it to an integer between one and the number by using the Math.floor
method.
Math
MethodsThe Math
object includes many methods beyond those you’ve looked at here. For example, Math.sin
and Math.cos
calculate sines and cosines. The Math
object also includes properties for various mathematical constants, such as Math.PI
. You can see a list of all the built-in methods you can use with the Math
object at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math#Methods.
Math
MethodsThe Math.random
method generates a random number between 0
and 1
. However, it’s essentially impossible for a computer to generate a truly random number. (It’s also hard for a human being to do so, which is why dice were invented.) Today’s computers do reasonably well at generating random numbers, but just how good is JavaScript’s Math.random
function? One way to test it is to generate many random numbers and calculate the average of all of them.
In theory, the average of all generated numbers should be somewhere near .5
, or halfway between 0
and 1
. The more random values you generate, the closer the average should get to this middle ground. To really do this test, you can create a script that tests JavaScript’s random number function by generating 5,000 random numbers and calculating their average.
This example will use a for
loop, which you’ll learn more about in the next lesson, but this is a simple enough example that you should be able to follow along. In this case, the for
loop will generate the random numbers. You’ll be surprised how fast JavaScript can do this.
To begin your script, initialize a variable called total
. This variable will store a running total of all the random values, so it’s important that it starts at 0
, like so:
var total = 0;
Next, begin a loop that will execute 5,000 times. Use a for
loop because you want it to execute for a fixed number of times (in this case 5,000):
for (i=1; i<=5000; i++) {
Within the for
loop, you need to create a random number and add its value to the total
variable. Here are the statements that do this and continue with the next iteration of the loop:
var num = Math.random();
total += num;
}
Depending on the speed of your computer, it might take a few seconds to generate those 5,000 random numbers. Just to be sure something is happening, you can have the script display a status message after each 1,000 numbers:
if (i % 1000 == 0) {
document.write("Generated " + i + " numbers...<br>");
}
Note
The %
symbol in the previous code is the modulo operator, which gives you the remainder after dividing one number by another. In this case it is used to find even multiples of 1,000.
The final part of your script calculates the average by dividing the value of the total
variable by 5,000. It also rounds the average to three decimal places, for fun:
var average = total / 5000;
average = Math.round(average * 1000) / 1000;
document.write("<h2>Average of 5000 numbers is: " + average + "</h2>");
To test this script and see just how random the numbers are, combine the complete script with an HTML document and <script>
tags. Listing 22.10 shows the complete random number testing script.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Math Example</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Math Example</h1>
<p>How random are JavaScript's random numbers?<br>
Let's generate 5000 of them and find out.</p>
<script>
var total = 0;
for (i=1; i<=5000; i++) {
var num = Math.random();
total += num;
if (i % 1000 == 0) {
document.write("Generated " + i + " numbers...<br>");
}
}
var average = total / 5000;
average = Math.round(average * 1000) / 1000;
document.write("<h2>Average of 5000 numbers is: " +
average + "</h2>");
</script>
</body>
</html>
To test the script, load the HTML document into a browser. After a short delay, you should see a result. If it’s close to .5
, the numbers are reasonably random. My result was .502
, as shown in Figure 22.7. If you reload the page, you’ll likely get different results, but they should all be around .5
.
Note
The average used here is called an arithmetic mean. This type of average isn’t a perfect way to test randomness. Actually, all it tests is the distribution of the numbers above and below .5
. For example, if the numbers turned out to be 2,500 .4
s and 2,500 .6
s, the average would be a perfect .5
—but the numbers wouldn’t be very random. (Thankfully, JavaScript’s random numbers don’t have this problem.)
The Date
object is a built-in JavaScript object that enables you to work more easily with dates and times. You can create a Date
object anytime you need to store a date and use the Date
object’s methods to work with the date.
You encountered one example of a Date
object in Lesson 4 with the time and date script. The Date
object has no properties of its own. To set or obtain values from a Date
object, use the methods described in the next section.
Note
JavaScript dates are stored as the number of milliseconds since midnight on January 1, 1970. This date is called the epoch. Dates before 1970 weren’t allowed in early versions but are now represented by negative numbers.
Date
ObjectYou can create a Date
object by using the new
keyword. You can also optionally specify the date to store in the object when you create it. You can use any of the following formats:
birthday = new Date();
birthday = new Date("November 1, 2014 08:00:00");
birthday = new Date(11,1, 2014);
birthday = new Date(11,1,2014, 8, 0, 0);
You can choose any of these formats, depending on which values you want to set. If you use no parameters, as in the first example, the current date is stored in the object. You can then set the values by using the set
methods, described in the next section.
Date
ValuesVarious set
methods enable you to set components of a Date
object to values:
setDate—Sets the day of the month.
setMonth—Sets the month, from 0
for January to 11
for December
setFullYear—Sets the year
setTime—Sets the time (and the date) by specifying the number of milliseconds since January 1, 1970
setHours, setMinutes, and setSeconds—Set the time
As an example, the following statement sets the year of a Date
object called holiday
to 2018:
holiday.setFullYear(2018);
Date
ValuesYou can use the get
methods to get values from a Date
object. This is the only way to obtain these values because they are not available as properties. Here are the available get
methods for dates:
getDate—Gets the day of the month
getMonth—Gets the month
getFullYear—Gets the four-digit year
getTime—Gets the time (and the date) as the number of milliseconds since January 1, 1970
getHours, getMinutes,getSeconds, and getMilliseconds—Get the components of the time
Note
Along with setFullYear
and getFullYear
, which require four-digit years, JavaScript includes the setYear
and getYear
methods, which use two-digit year values.
Finally, a few functions are available to help your Date
objects work with local time values and time zones:
getTimeZoneOffset—Gives you the local time zone’s offset from UTC (Coordinated Universal Time, based on the old Greenwich Mean Time standard). In this case, local refers to the location of the browser. (Of course, this works only if the user has set his or her system clock accurately.)
toUTCString—Converts the date
object’s time value to text, using UTC.
toLocalString—Converts the date
object’s time value to text, using local time.
Along with these basic functions, JavaScript includes UTC versions of several of the functions described previously. These are identical to the regular commands but work with UTC instead of local time:
getUTCDate—Gets the day of the month in UTC time
getUTCDay—Gets the day of the week in UTC time
getUTCFullYear—Gets the four-digit year in UTC time
getUTCMonth—Returns the month of the year in UTC time
getUTCHours, getUTCMinutes, getUTCSeconds, and getUTCMilliseconds—Return the components of the time in UTC
setUTCDate, setUTCFullYear, setUTCMonth, setUTCHours, setUTCMinutes, setUTCSeconds, and setUTCMilliseconds—Set the time in UTC
Two special methods of the Date
object enable you to convert between date formats:
Date.parse—Converts a date string, such as March 1, 2018
, to a Date
object (the number of milliseconds since 1/1/1970)
Date.UTC—Converts a Date
object value (the number of milliseconds) to a UTC (GMT) time
Instead of using these methods with a Date
object you have created, you use them with the built-in object Date
.
In this lesson, we focused on variables and how JavaScript handles them. You’ve learned how to name variables, how to declare them, and the differences between local and global variables. You also explored the data types supported by JavaScript and how to convert between them.
You learned about JavaScript’s more complex variable types—strings and arrays—and looked at features that enable you to perform operations on them, such as converting strings to uppercase and sorting arrays.
You learned several important features of JavaScript in this lesson. First, you learned how to use functions to group JavaScript statements and how to call functions and use the values they return. Next, you learned about JavaScript’s object-oriented features—defining objects with constructors, creating object instances, and working with properties, property values, and methods.
As an example of these object-oriented features, you looked more closely at the Math
and Date
built-in JavaScript objects and learned more than you ever wanted to know about random numbers.
Q. What is the importance of the var
keyword? Should I always use it to declare variables?
A. You only need to use var
to define a local variable in a function. However, if you’re unsure at all, it’s always safe to use var
. Using it consistently will help you keep your scripts organized and error free.
Q. Is there any reason I would want to use the var
keyword to create a local variable with the same name as a global one?
A. Not on purpose. The main reason to use var
is to avoid conflicts with global variables you might not know about. For example, you might add a global variable in the future, or you might add another script to the page that uses a similar variable name. This is more of an issue with large, complex scripts.
Q. What good are Boolean variables?
A. Often in scripts you’ll need a variable to indicate whether something has happened—for example, whether a phone number the user has entered is in the right format. Boolean variables are ideal for this; they’re also useful in working with conditions, as you’ll see in Lesson 23.
Q. Can I store other types of data in an array? For example, can I have an array of dates?
A. Absolutely. JavaScript enables you to store any data type in an array.
Q. Many objects in JavaScript, such as DOM objects, include parent and child objects. Can I include child objects in my custom object definitions?
A. Yes. Just create a constructor function for the child object and then add a property to the parent object that corresponds to it. For example, if you created a Nicknames
object to store several nicknames for a person in the card file example, you could add it as a child object in the Card
object’s constructor: this.nick = new Nicknames();
.
Q. Can I create an array of custom objects?
A. Yes. First, create the object definition as usual and define an array with the required number of elements. Then assign a new object to each array element (for example, cardarray[1] = new Card();
). You can use a loop, as described in the next lesson, to assign objects to an entire array at once.
Q. Can I modify all properties of objects?
A. With custom objects, yes—but this varies with built-in objects and DOM objects. For example, you can use the length
property to find the length of a string, but it is a read-only property and cannot be modified.
The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.
1. Which of the following is not a valid JavaScript variable name?
2names
first_and_last_names
FirstAndLast
2. If the statement var fig=2
appears in a function, which type of variable does it declare?
A global variable
A local variable
A constant variable
3. If the string test
contains the value The eagle has landed.
, what would be the value of test.length
?
4
21
The
4. Using the same sample string, which of these statements would return the word eagle
?
test.substring(4,9)
test.substring(5,9)
test.substring("eagle")
5. What will be the result of the JavaScript expression 31 + " angry polar bears"
?
An error message
32
"31 angry polar bears"
6. What JavaScript keyword is used to create an instance of an object?
object
new
instance
7. What is the meaning of the this
keyword in JavaScript?
It refers to the current object.
It refers to the current script.
It has no meaning.
8. Which of the following objects cannot be used with the new
keyword?
Date
Math
String
9. How does JavaScript store dates in a Date
object?
The number of milliseconds since January 1, 1970
The number of days since January 1, 1900
The number of seconds since Netscape’s public stock offering
10. What is the range of random numbers generated by the Math.random
function?
Between 1
and 100
Between 1
and the number of milliseconds since January 1, 1970
Between 0
and 1
Note
Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.
1. a. 2names
is an invalid JavaScript variable name because it begins with a number. The others are valid, although they’re probably not ideal choices for names.
2. b. Because the variable is declared in a function, it is a local variable. The var
keyword ensures that a local variable is created.
3. b. The length of the string is 21 characters.
4. a. The correct statement is test.substring(4,9)
. Remember that the indexes start with 0
and that the second index is noninclusive.
5. c. JavaScript converts the whole expression to the string "31 angry polar bears"
. (We mean no offense to polar bears, who are seldom angry and are rarely seen in groups this large.)
6. b. The new
keyword creates an object instance.
7. a. The this
keyword refers to the current object.
8. b. The Math
object is static; you can’t create a Math
object.
9. a. Dates are stored as the number of milliseconds since January 1, 1970.
10. c. JavaScript’s random numbers are between 0
and 1
.
Modify the sorting example in Listing 22.3 to convert the names to all uppercase and display a numbered list of names in the <textarea>
.
Modify the definition of the Card
object to include a property called personal_notes
to store your own notes about the person. Modify the object definition and printCard
function in Listings 22.7 and 22.8 to include this property.
Modify the random number script in Listing 22.10 to run three times to calculate a total of 15,000 random numbers and then display a separate total for each set of 5,000 numbers. (Hint: You’ll need to use another for
loop that encloses most of the script.)
54.160.133.33