Chapter 7. Objects and Built-In Types

You live in an object-based world. Stop and think about the objects you come in contact with pretty much every second of every day. Whether you're driving to work or school, sitting at a table eating dinner, sleeping in a bed, or even walking in a field — you're interacting with objects. You don't even think about most of the objects you come in contact with every day. Interaction with objects is natural to you.

Before the 1990s, programmers primarily used procedural programming languages. These languages were based on the steps a program takes to reach the desired goal — very much like the examples thus far in this book. It wasn't until the 1990s that mainstream developers began to shift their thinking to involve objects.

Objects are a very important part of JavaScript: In fact, just about everything in JavaScript is an object. An understanding of what objects are and how to use them is required in order to use the language to its full potential. First let's talk a little more about what objects are and why they're useful.

WHAT ARE OBJECTS?

It's easiest to understand objects in a programming context by comparing them with real-world examples. Consider an automobile as an example. Automobiles come in a variety of colors, and are made by manufacturers that build them into different models. Some have vinyl interiors, while others have leather. Most automobiles come with an automatic transmission, and a small number of them have manual transmissions. The majority of automobiles have four wheels, and others have more than four. There are a variety of properties, or pieces of data, that help describe each individual automobile on the planet.

Automobiles are also defined by a set of actions they can perform. They propel themselves forward or backward by supplying fuel to an engine. They can change directions by moving their wheels to the right or left. They even have a communication device (the horn) that can honk to get the attention of another driver. These are methods, or actions, a driver can use to control an automobile.

In programming, objects are things that can have properties, or special variables, that contain data about them. They also have methods, which are similar to functions, which perform some type of action — usually on the data stored in properties. Just as the properties and methods of an automobile object define an automobile, the properties and methods of an object in programming define that object. Object-oriented programming is a type of programming intended to mimic the real world by using objects to organize and work with data — complex data, as opposed to the simple primitive data discussed in Lesson 2.

JavaScript has many object data types. Before looking into them, however, first look at how to use objects.

USING JAVASCRIPT OBJECTS

An object must be created before it can be used, and the most common way to create an object is by calling a constructor. A constructor is a special function that creates an instance of a particular data type.

Think back to Lesson 2, and recall the primitive data types in JavaScript: Number, String, and Boolean. While these primitive data types are not objects themselves, they do have what are called wrapper objects — objects that encapsulate the primitive types so that they can be represented as objects. Because of this, it's possible to create values of these types by using the appropriate constructors. A constructor has the same name as the data type it represents. For example, the String data type's constructor is String().

When calling a constructor, you use an operator called new. This tells JavaScript that you want to create a new object of the specified data type. After typing the new operator, you then call the data type's constructor function and pass it any necessary parameters. The following code shows an example of using a constructor to create a String object:

var message = new String("Hello, World!");

This is a variable-initialization statement that creates a String object containing the data "Hello, World!" and assigns it to the message variable.

Note

Even though you can create a String value, or a value of any of the other primitive types, by calling its constructor, it is recommended that you use literal notation to create such values. You can still access the properties and methods of those data types.

Once an object is created, it is then possible to use the properties and methods (collectively known as members) of that data type. Accessing a data type's members involves the use of the dot (.) operator. Use this operator between the object's identifier and the member's identifier, like this:

var numberOfCharacters = message.length; // 13

This statement uses the String data type's length property, which returns the amount of characters and whitespace in the string. The property is accessed by means of the object's identifier (message in this code), followed by the dot operator, and then the property's identifier (length).

Properties are very much like variables attached to an object. Some properties are read-only — meaning they can return data, but they cannot be assigned a new value. The String data type's length property is a read-only property. Because of this, the following line is incorrect:

message.length = 10; // wrong; length is read-only

Accessing methods follows the same principle: use the object's identifier, followed by a dot, and then the method's identifier. The following code calls one of the String data type's methods:

var lowerCaseMessage = message.toLowerCase(); // "hello, world!"

Just as properties are like variables, methods are like functions. The primary difference between a method and a function is that methods perform some kind of work on or for the object. The toLowerCase() method is an example of this. It performs work using the String object's value by copying and converting all alphabetical characters to lowercase and returning the new value to the caller, the lowerCaseMessage variable in this code.

Now that you have an idea of how to use objects, let's start looking at JavaScript's built-in data types.

BUILT-IN DATA TYPES

JavaScript has many built-in data types. This lesson introduces you to the following types:

  • Array

  • Date

  • Number

  • String

Future lessons will introduce you to the Object and Function data types.

Array

Expanding on the automobile example at the beginning of this lesson, an automobile has a set of gears that determine how the vehicle moves. Putting an automobile into reverse moves it backward, whereas another gear moves the vehicle forward. Storing all possible gear values in an object's property could be problematic, as properties and variables typically contain only one piece of data at a time. The following code provides an example:

var gear = 1;

There are times, such as in the gear situation, when it's desirable to store multiple values in one variable or property. This is where arrays are helpful. The simplest definition of an array is an ordered collection of values.

Arrays are created in one of two ways. The first way uses the Array data type's constructor, like this:

var myArray = new Array(); // create a new array

The Array() constructor can accept a set of parameters containing the data to store in an array. The following line of code creates an array and adds possible values for an automobile's gears:

var gears = new Array(1, 2, 3);

This array is said to have three elements, or items. There is a much shorter and preferred method of creating arrays, however. By using array literal notation, you can create the same arrays with fewer keystrokes:

var myArray = [];
var gears = [ 1, 2, 3 ];

Array literal notation involves the use of square brackets, as shown in this code. The use of square brackets is a result of how you access each individual element in the array: index notation. You first use the array's identifier, followed by an opening square bracket, followed by the element's index, and then the closing square bracket.

Elements in an array are stored in a numerical sequence starting with zero. Remember from Lesson 5 when examples showed loops starting at zero? This is why. The first element in an array has an index of 0. The second element has an index of 1, the third element has an index of 2, and so on. You use an element's index number to access it in the array. The code to retrieve the third element in the gears array looks like this:

gears[2]; // 3

The code to retrieve the first element in the gears array looks like this:

gears[0]; // 1

It's OK if this is confusing to you, as it usually is for beginning developers. As humans, we typically start counting with the number one. Computers don't — they start counting at zero. JavaScript, as well as many other languages, follows the computer's pattern and starts counting at zero too. This means that counting to 10 actually involves 11 numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. This is an important concept to understand, as this counting method is used throughout the language.

Each element in an array is very much like a variable; you can get data as shown in the previous examples or you can modify existing elements by assigning them new data. The following code changes the first element in the array:

gears[0] = 2; // changed from 1 to 2
gears[0] = 1; // changed back to 1

It's exactly like using normal variables, except you use index notation to access an element in the array.

The gears array has three elements, and this information is retrieved by means of the Array type's length property. It behaves much like the String type's length property, except that instead of counting characters, it counts the number of elements in the array. The following code shows an example of the length property:

var length = gears.length; // 3

The length property is especially useful when you're using a loop to iterate over an array. Instead of programming a specific end point for the loop, the length property can ensure that the loop iterates over each element and ends after the last element. The following code shows this:

for (var i = 0; i < gears.length; i++) {
    alert(gears[i]);
}

This code is the basis for looping through an array. The initialization portion of the for loop initializes a variable called i with a value of 0. The loop's condition tells the loop to repeat itself as long as i is less than the length of the gears array. It will iterate three times, and the value of i for each iteration is: 0, 1, 2. On the fourth iteration, the condition determines if i, which contains a value of 3, is less than the length of the gears array, which also is 3. Because 3 is not less than 3, the loop exits.

The length property always returns the number of elements in the array. This means that adding a new element to the gears array will cause gears.length to return 4. One way to add a new element to an array is to use index notation. The following line adds a new element to represent the gear of reverse:

gears[3] = −1;

This code adds a new element in an index position of 3, which is the fourth position in the array. While hard-coding the index position works in some cases, such as this example, there are times when you will not know how many elements are in an array. In times like these you can use the length property to add the new element at the next index position. For more flexible code, the previous line of code could be rewritten like this:

gears[gears.length] = −1;

In this example, the length property returns a value of 3, which is also the index number needed to add a new element at the end of the array. There is an easier way to achieve the same results, however, and it requires the use of one of the Array type's methods: the push() method, shown here:

gears.push(−1);

The push() method accepts one argument: the value to add to the array. Now that a new element has been added to the array, the length property returns 4 since there are now four elements in the array: 1, 2, 3, and −1.

As well as the push() method, the Array data type exposes a few other useful methods, as shown in the following table:

Useful Array Methods

METHOD

DESCRIPTION

concat(array1, array2, ...)

Joins two or more arrays into a single array.

join(separator)

Converts the array into a string. Each element is separated by the specified separator.

pop()

Removes the last element of the array and returns it to the caller.

push(element)

Adds a new element to the end of the array. Returns the new length.

reverse()

Reverses the order of the elements in the array.

sort()

Sorts the elements in the array.

The next few sections show you how to use some of these methods.

Joining Arrays

If you want to join multiple arrays together, you can use the concat() method. It does not alter the original arrays; instead, it creates a new array, populates it with the elements of all the specified arrays, and returns it to the caller. Let's depart from the automobile example and look at a family, as shown in this example:

var parents = ["John", "Jane" ];
var kids = [ "Jason", "Joe", "Jordan" ];
var pets = [ "Jackson", "Jimmy" ];
var family = parents.concat(kids, pets);

The first three lines of this code create three arrays, all representing portions of a family — the names of the parents, children, and pets. The final line of this code calls the concat() method on the parents array and passes the kids and pets arrays to the method. The newly created array, family, contains all the elements of the other arrays. This means family contains the names: John, Jane, Jason, Joe, Jordan, Jackson, and Jimmy.

The order in which the concat() method is called determines the order of the elements in the new array. In this example concat() is called on the parents array, so the elements in this array are the first elements in family. The kids array is the first argument passed to the method, so its elements can be found after John and Jane in family. The pets array is the last argument passed to concat(), so its elements appear at the end of family. Changing how concat() is called changes the order in which the provided arrays are joined together. For example, if the final line is var family = pets.concat(parents, kids), the elements of family would be in this order: Jackson, Jimmy, John, Jane, Jason, Joe, and Jordan.

Converting Arrays to Strings

Sometimes it's beneficial to convert an array to a string. In fact, it's more efficient to do this than to concatenate several strings together. Use the join() method to join the individual elements into a single string. It accepts one argument, specifying a separator to place between the element values. The following example uses the original family array from the previous section:

var familyString = family.join(", ");

This code passes a comma followed by a whitespace character to the join() method called on the family array. This results in familyString, containing the value "John, Jane, Jason, Joe, Jordan, Jackson, Jimmy". The separator passed to the method separates the element's values in the string.

As mentioned earlier, it's more efficient to use the join() method to concatenate array elements than it is to use the + operator to concatenate strings. For this reason you will see developers use something like the following code to generate strings:

var stringParts = [
    "John's family is: ",
    family.join(", ")
];

var familyString = stringParts.join("");

This code first creates an array called stringParts. Its first element is a string value, and its second element is the result of converting the family array. The final result of this code is the string "John's family is: John, Jane, Jason, Joe, Jordan, Jackon, Jimmy".

Like the concat() method, the join() method does not alter the original array.

Sorting Elements

Arrays are typically used for organizing similar pieces of data. Therefore, it might be desirable to sort that data in alphabetical order if the elements are string values or in numerical order if the data consists of numbers.

The sort() method makes sorting easy: It sorts the elements of the array in alphabetical order. The following example uses the family array yet again:

family.sort();

Unlike the other methods before it, the sort() method alters the original array The elements contained within family are now in the following order: Jackson, Jane, Jason, Jimmy, Joe, John, and Jordan.

The sort() method is case-sensitive: Words starting with an uppercase letter come before words starting with a lowercase letter. So Jackson comes before jackson as the result of a sort in JavaScript.

The sort() method sorts the elements in ascending order: There is not a method or a parameter to sort in descending order. However, there is a method, called reverse(), that can reverse the order of an ascending-ordered array.

Reversing Elements

The reverse() method alters the array by reversing the order of the array's elements. To get an idea of how this works, let's look at the kids array from an earlier section:

var kids = [ "Jason", "Joe", "Jordan" ];
kids.reverse();

The original kids array can be represented as in the following table:

INDEX

ELEMENT VALUE

0

Jason

1

Joe

2

Jordan

This table shows each element in the array and its index position. Calling the reverse() method reorders the elements in the array in reverse order, and the elements receive new index positions. The following table shows the array after calling reverse():

INDEX

ELEMENT VALUE

0

Jordan

1

Joe

2

Jason

By combining the use of sort() and reverse() methods, you can essentially sort an array in descending order, as in the following code:

family.sort().reverse();

Remember that many of the Array object methods return an array; sort() is one such method. Because of this, it's possible to chain method calls to perform multiple processes in a single statement. The call to sort() returns the sorted version of the family array, but instead of the result's being assigned to a variable, the return value is used to call the reverse() method. This is just one technique experienced developers use to write more efficient code.

Date

Every computer system needs to maintain date and time functionality. Many of today's operating systems rely on date and time to provide essential information and services. Similarly, every programming language needs some way to get the current date and time so that programmers can write meaningful and usable applications.

JavaScript uses the Date data type to handle this functionality. It provides access to information such as the current date and time, as well as any other date and time, so calculations can be performed. JavaScript's Date object uses the UNIX timestamp; in fact, it stores date information in this format. The UNIX timestamp is the number of milliseconds since the UNIX Epoch, January 1, 1970 at 12:00 a.m. GMT. For example, the UNIX timestamp for January 1, 2010 at 12:00 a.m. GMT is 1264982400000. The date and time contained within a Date object are based on your computer's date and time.

There are four ways to create a Date object. The first is the simplest, and it returns the current date and time. Simply call the constructor without passing any arguments to it, like this:

var date = new Date(); // current date and time

The second way to create a Date object is to pass a year, month, day, hours, minutes, seconds, and milliseconds to the Date constructor:

var date = new Date(2010, 0, 1, 0, 0, 0, 0); // January 1, 2010 12:00AM
var date2 = new Date(2010, 0, 1); // January 1, 2010 12:00AM

Most parameters are optional; omitting them causes 0 to be passed in their place. An important note to make here is that the month argument is passed as a zero-based number. So January is 0, February is 1, March is 2, and so on. If you are specifying hours, they must be passed in 24-hour format: 0 is midnight, 13 is 1:00 p.m., and 23 is 11:00 p.m.

You can also create Date objects by passing a string value, like this:

var date = new Date("January 1, 2010");
var date2 = new Date("Jan 1 2010");
var date3 = new Date("1 January 2010");

There are a variety of string variations you can pass to the constructor. If in doubt, try it out. Browsers, however, behave differently in creating a Date object this way. For example, Firefox does not support "01-01-2010" as a valid date format. So make sure to test Date object creation in multiple browsers when passing a string to the constructor.

The final way to create a Date object is to pass it a UNIX timestamp. This is perhaps the least-used method of Date object creation. The following line creates a Date object by passing a UNIX timestamp:

var copy = new Date(date.getTime()); // January 1, 2010 12:00AM

The Date object's getTime() method returns the UNIX timestamp of the Date object it was called on. So, this code makes a copy of the date Date object from the previous example by calling its getTime() method, passing it to the Date constructor, and assigning the new Date object to the copy variable.

JavaScript stores dates and times in UNIX timestamps. This isn't useful, so the Date data type exposes some methods that allow you to get more meaningful information from a Date object. The following table lists the more useful methods involving dates.

Date-Related Methods

METHOD

DESCRIPTION

getFullYear()

Returns the four-digit year.

getMonth()

Returns a zero-based number representing the month. January is 0, February is 1, and December is 11.

getDate()

Returns a number representing the day of the month.

getDay()

Returns a zero-based number representing the day of the week. Sunday is 0, Monday is 1, and Saturday is 6.

toDateString()

Converts the date portion of the object to a string and returns it in the format of Fri Jan 1 2010.

setDate(dayOfMonth)

Sets the day of the month according to the argument passed as dayOfMonth.

setMonth(monthNumber)

Sets the month according to the argument passed as monthNumber. Valid values are 0 through 11.

setFullYear(yearNumber)

Sets the year according to the four-digit year passed as yearNumber.

Unfortunately, the Date object does not return the name of the month or the day of the week; developers have to provide that functionality in their code. With arrays, however, it's a simple exercise. Look at this code:

var daysOfWeek = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday" ];

var date = new Date(); // get current date

alert("Today is " + daysOfWeek[date.getDay()]);

The result of running this code depends on the day on which it is executed. If it were run on January 1, 2010, the alert window would display the text, "Today is Friday." Because array indexes are zero-based, as is the getDay() method of the Date object, you can use the value returned by getDay() as the index for the correct day of the week. The same principle can be applied to months, which you'll see in the Try It section later.

Just as JavaScript's Date data type has methods for working with dates, it also exposes methods to work with the time portion of a Date object. The following table lists these time-based methods:

Time Related Methods

Method

Description

getHours()

Returns the hour in 24-hour format. Possible values are 0 through 23.

getMinutes()

Returns the minutes. Possible values are 0 through 59.

getSeconds()

Returns the seconds. Possible values are 0 through 59.

getMilliseconds()

Returns the milliseconds. Values range from 0 to 999.

setHours(newHour)

Sets the hours according to the argument newHours. Valid values for argument are 0 through 23.

setMinutes(newMinutes)

Sets the minutes according to the argument newMinutes. Valid values for argument are 0 through 59.

setSeconds(newSeconds)

Sets the seconds according to the argument newSeconds. Valid values for argument are 0 through 59.

setMilliseconds(newMS)

Sets the milliseconds according to the argument newMS. Valid values for argument are 0 through 999.

NUMBER

Lesson 2 thoroughly covered the Number data type. Number objects do not have any properties, but they do have some methods. The most useful, and perhaps the most used, Number method is the toFixed() method. This method formats the number to a fixed amount of decimal places, like this:

var num = 1.2345;
var fixedNum = num.toFixed(2); // 1.23

It accepts one argument specifying the amount of decimal places to include in the new number. It does not modify the original number; it copies it, formats the copy, and returns the copy to the caller.

The toFixed() method rounds the nearest decimal place up or down. The previous example looked at the decimal place after the hundredths and determined that it should be rounded down. The next example uses the toFixed() method to round up:

var num = 1.54321;
var fixedNum = num.toFixed(0); // 2

This code chops all decimal places off the number. The toFixed() number looks at the first decimal place to determine whether to round the number up or down. Since it is greater than or equal to five, toFixed() rounds the number up to 2.

The toFixed() method can chop off only zero to 20 decimal places.

String

The beginning of this lesson introduced you to two members of the String data type: the length property and the toLowerCase() method. The length property is String's only property, but unlike the Number type, the String type has a multitude of useful methods. They don't alter the original string in any way. Instead, they make a copy, perform their operation on the copy, and return the copy to their caller.

The following table lists several useful String methods that will be covered in this section:

Useful String Methods

METHOD

DESCRIPTION

charAt(index)

Gets the character at the specified index.

indexOf(searchString)

Returns the index position of the first found occurrence of the provided string. Returns −1 if no match was found.

lastIndexOf(searchString)

Returns the index position of the last found occurrence of the provided string. Returns −1 if no match was found.

replace(toReplace, replaceWith)

Searches for a substring in the string that matches the provided toReplace argument, and replaces the first match with the provided replaceWith.

split(separator)

Splits a string into an array using the provided separator.

substr(startIndex, numberOfChars)

Extracts the characters of the string starting at the startIndex position and selecting the amount of characters specified by numberOfChars. Omitting numberOfChars selects the remainder of the string.

substring(startIndex, endIndex)

Extracts the characters from the string starting at the position specified by startIndex and ending with the character before endIndex. Omitting endIndex results in the rest of the string's being selected.

toLowerCase()

Returns the string in all-lowercase characters.

toUpperCase()

Returns the string in all-uppercase characters.

Searching for Substrings

String objects have two useful methods to search for substrings, or smaller strings that occur within a larger string. They are the indexOf() and lastIndexOf() methods. These methods are useful when you want to determine if a particular string contains a keyword or phrase. Both methods accept a substring as an argument, and JavaScript will search for that substring within the String object the method is called on. These methods are case-sensitive: They do not report a match unless an exact match is found.

The difference between the two methods is how they search for the substring. Look at the following example:

var welcomeString = "Hello, Jeremy! Wonderful day, isn't it, Jeremy?";

alert(welcomeString.indexOf("Jeremy")); // 7
alert(welcomeString.lastIndexOf("Jeremy")); // 40
alert(welcomeString.indexOf("JavaScript")); // −1

The indexOf() method begins searching at the beginning of the string for the specified substring. It then starts searching the string and doesn't stop until it either finds a match or reaches the end of the string. When it finds a match, it immediately returns the index of the match. In this code, indexOf("Jeremy") returns 7 because the substring was found starting at the seventh character position.

The lastIndexOf() method begins searching at the end of the string as opposed to the beginning, and it doesn't stop until it either finds a match or reaches the beginning of the string. When it finds a match of the specified substring, it, too, immediately returns the index position of the match. In this example, lastIndexOf() finds a match that starts at an index position of 40.

If indexOf() or lastIndexOf() does not find a match, it returns a value of −1.

Extracting Substrings

There are times when extracting pieces of a string is beneficial, and JavaScript's String data type allows this with the substr() and substring() methods. Both of these methods provide the same end result, but they do so based on different parameter values.

The substr() method accepts two parameters. The first is required, and it's the index at which to start the extraction. The second parameter is optional. If specified, it determines how many characters after the starting index to extract, including the starting character. If the second parameter is omitted, the substr() method extracts all characters after the starting index. The following code uses the substr() method to extract a portion of a string:

var message = "JavaScript 24-Hour Trainer";
var subString = message.substr(11, 7); // 24-Hour

This code uses the substr() method to extract the 24-Hour portion of the string contained within the message variable. The 2 in 24-Hour is the twelfth character in the string — making the starting index 11 (again, remember that indexes start at 0) — and the phrase is 7 characters long. Passing these two values to the substr() method extracts the phrase 24-Hour and assigns it to the subString variable. The string contained within message is not altered.

The substring() method can provide the same results, but it does so with slightly different data. It still requires a starting index, and the substring() method behaves like substr() if the second parameter is omitted. But if it is specified, it is the index at which to stop the extraction. An important, and often forgotten, behavior of the substring() method is that the extraction includes the characters up to the ending index; it does not include the character at the ending index. The following code rewrites the previous example by using the substring() method:

var message = "JavaScript 24-Hour Trainer";
var substring = message.substring(11, 18); // 24-Hour

Use the method that makes the most sense to you. The substr() method is obviously the better choice if you know the exact length of the desired substring. The substring() method is the better choice when you don't know how long the desired substring is, and can be a powerful tool combined with the indexOf() and lastIndexOf() methods.

Converting to an Array

In many ways strings are closely related to arrays. In fact, many programming languages see a string as an array of characters. Unfortunately, JavaScript is not one of these languages. While String objects have a length property like array objects, you cannot use index notation to access individual characters as you can with elements in an array. Instead, String objects have a charAt() method. Pass an index to this method and you can retrieve, but not edit, an individual character at the specified index.

It is possible, however, to convert a string to an array by using the split() method: it splits a string into an array of substrings. The method knows where to split the string according to the argument passed to it. If you supply an empty string as an argument, this method creates an array in which each individual character is an element. The following code demonstrates this:

var message = "Hello, World!";
var messageArray = message.split(""); // converts to array

Once the string is in array form, you can access the individual characters using index notation. This method is also quite useful when you have a string containing a list of items delimited by a consistent delimiting character, such as a comma. Look at this code:

var fruitsString = "orange,apple,banana";
var fruitsArray = fruitsString.split(","); // creates array with 3 elements

This code creates an array by splitting the fruitsString string at each comma. The resulting array contains three elements: orange, apple, and banana.

Replacing Text

The replace() method accepts two arguments: the string to replace, and the string to replace it with. This method searches the string starting at the beginning and looks for the first occurrence of the specified substring. It does not replace all occurrences of the specified substring — only the first, as shown in the following code:

var message = "Today is Monday. Yesterday was Monday.";
var newMessage = message.replace("Monday", "Tuesday");
alert(newMessage); // Today is Tuesday. Yesterday was Monday.

This code first creates a string value that contains an error. It says that today is Monday and yesterday was Monday. To fix this error, the second line of code uses the replace() method to change "Monday" to "Tuesday" and returns the new string to the newMessage variable. When the alert window displays the new message, it reads, "Today is Tuesday. Yesterday was Monday."

As with all the other String methods discussed in this lesson, the original string (message in this case) is not altered.

TRY IT

In this lesson, you learn how to use objects and some of JavaScript's built-in object types. Here, you apply some of the knowledge and concepts you gained from previous sections.

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or they can download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson07 in the JS24Hour folder you created in Lesson 1. Store the files you create in this lesson in the Lesson07 folder.

Step-by-Step

Write an application that prompts the user to enter his or her name. Display the name and today's date in an alert window. Use a function to get the name of the month, and use another function to abbreviate it to three characters.

  1. Open your text editor and type the following function.

    function getMonthName(index) {
        var months = [ "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" ];
    
        return months[index];
    }

    This getMonthName() function creates an array containing the names of the month, and returns the element at the provided index.

  2. Now add the following bolded function:

    function getMonthName(index) {
        var months = [ "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" ];
    
        return months[index];
    }
    function abbrName(text) {
        return text.substr(0, 3);
    }

    This new function, abbrName(), uses the substr() method to select the first three characters of the provided text and returns it to the caller.

  3. Add the following bolded code:

    function getMonthName(index) {
        var months = [ "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" ];
    
        return months[index];
    }
    
    function abbrName(text) {
        return text.substr(0, 3);
    }
    
    var date = new Date();
    var messageParts = [
        "Hello, ",
        prompt("Please enter your name", "Please enter your name"),
        ". Today is ",
        abbrName(getMonthName(date.getMonth())),
        " ",
        date.getDate(),
        ", ",
        date.getFullYear()
    ];

    The first line of this code creates a Date object containing today's date. This Date object will be used to display date information to the user.

    The second statement creates an array called messageParts. This array's purpose is to contain elements that will be concatenated into the message to display to the user. The first element is a simple string. The second element calls the prompt() function to prompt the user to enter his or her name. The fourth element gets the current month from the date object and passes it to the getMonthName() function. The return value of getMonthName() is then passed to the abbrName() function. So the fourth element in the array is a string containing the first three characters of the current month.

  4. Alert the user to the message by adding the following bolded code:

    function getMonthName(index) {
        var months = [ "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" ];
    
        return months[index];
    }
    
    function abbrName(text) {
        return text.substr(0, 3);
    }
    
    var date = new Date();
    var messageParts = [
        "Hello, ",
        prompt("Please enter your name", "Please enter your name"),
        ". Today is ",
        abbrName(getMonthName(date.getMonth())),
        " ",
        date.getDate(),
        ", ",
        date.getFullYear()
    ];
    
    alert(messageParts.join(""));

    This line calls the join() method, passing it an empty string to concatenate the elements without a noticeable separator.

  5. Save the file as lesson07_sample01.js.

  6. Open another instance of your text editor, type the following HTML, and save it as lesson07_sample01.htm.

    <html>
    <head>
        <title>Lesson 7: Objects</title>
    </head>
    <body>
        <script type="text/javascript" src="lesson07_sample01.js"></script>
    </body>
    </html>
  7. Open the HTML file in your browser. An alert window will display the name provided to the prompt window in a message containing today's date.

Note

Please select Lesson 7 on the DVD to view the video that accompanies this lesson. You can also download the sample code for all lessons from the book's website at www.wrox.com.

Step-by-Step
..................Content has been hidden....................

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