|Language:||English, Spanish, Arabic|
|Genre:||Business & Career|
|Distribution:||Free* [*Registration Required]|
We will now look at some of the details. Using Variables, Strings, and Arrays Choosing Variable Names Variables are named containers that can store data for example, a number, a text string, or an object. As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name: Variable names can include letters of the alphabet, both upper- and lower- case.
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—totalnum, Totalnum, and TotalNum are separate variable names.
There is no official limit on the length of variable names, but they must fit within one line. Using these rules, the following are examples of valid variable names: Do yourself a favor: Use longer, friendly names whenever possible.
To understand where to declare a variable, you will need to understand the concept of scope. There are two types of variables: Global variables have the entire script and other scripts in the same HTML doc- ument as their scope.
They can be used anywhere, even within functions. Using Variables 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: If this statement is used outside functions, it creates a global variable. The var key- word is optional in this case, so this statement is equivalent to the previous one: Way A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. To create a local variable within a function, you must use the var keyword.
If the operator is before the variable name, the increment or decrement hap- pens before the current expression is evaluated. This difference is only an issue 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 The following two statements have differ- ent effects: The second statement first increments lines to 41, then displays an alert with the value By the These operators are strictly for your convenience.
The nonnumeric portion of the string is ignored. By the These functions look for a number of the appropriate type at the beginning of the Way string. If a valid number is not found, the function will return the special value NaN, meaning not a number. 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 vari- able called test: There are two ways to create a new String object.
Assigning a Value You can assign a value to a string in the same way as any other variable. Both of the examples in the previous section assigned an initial value to the string. You can also assign a value after the string has already been created. For example, the fol- lowing statement replaces the contents of the test variable with a new string: Listing 6. For example, this statement adds a period to the current contents of the string sentence: The browser knows By the whether to use addition or concatenation based on the types of data you use with Way the plus sign.
If you use it between a number and a string, the number is convert- ed to a string and concatenated. You can do this with the length property of String objects, which you can use with any string. For example, test.
Here is an exam- ple of this property: The sec- ond statement displays the length of the string—in this case, 15 characters. Remember that although test refers to a string variable, the value of By the test. For example, the following statement displays the value of the test string variable in lowercase: The toUpperCase and toLowerCase methods do not take any parameters, but you still need to use the parentheses.
These are explained in the following sections. Using Part of a String 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 text string: There are three things you need to understand about the index parameters: Indexing starts with 0 for the first character of the string, so the fourth charac- ter is actually index 3. The second index is noninclusive. A second index of 6 includes up to index 5 the sixth character. Working with Substrings 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 have pro- duced the same result. Of course, there is rarely a reason to use the reverse order. As another example, suppose you defined a string called alpha to hold the alphabet: This is true whenever the two index values are the same.
Getting a Single Character The charAt method is a simple way to grab a single character from a string. The indexes begin at 0 for the first character. Here are a few examples using the alpha string: Using Variables, Strings, and Arrays Finding a Substring 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.
Way Make sure you type it exactly as shown here when you use it in scripts. The value returned in the loc 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 to indicate the index value to begin the search. For example, this statement searches for the word fish in the temp string, starting with the 20th character: 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 backwards, starting with the last character. For example, this statement finds the last occurrence of Fred in the names string: In this case, the string will be searched backward starting at that location. Using Numeric Arrays 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.
This tells you the number of elements in the array. For example, these statements would print the number Using Variables, Strings, and Arrays 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: Accessing Array Elements You can read the contents of an array using the same notation you used when assigning values.
For example, the following statements initialize an array of four names and sort it: If an array contains the numbers 4, 10, 30, and , for example, it would sort them as 10, , 30, 4—not even close.
This is why a-b is all you need for the function to sort numerically. You will create this file next. This document defines a form named theform, a text field named newname, an addname button, and a textarea named sorted.
When you type a name into the text field and click the button, the onclick event han- dler calls the SortNames function.
This function stores the text field value in a vari- able, thename, and then adds the name to the names array using numnames as the index. It then increments numnames 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. You can then add some names and test the script.
This is useful for repeating sections of code, and you can also create functions that accept parameters and return val- ues for later use. Whereas functions enable you to group sections of code, objects enable you to group data—you can use them to combine related data items and functions for working with the data.
Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To use a function, you must first define it. Here is a simple example of a function defi- nition: This begins with the function keyword.
You use these to enclose all of the statements in the function. The browser uses the braces to determine where the function begins and ends.
Between the braces, this particular function contains a single line. This uses the built-in alert function, which displays an alert message. If you define a function such as Greet with a Way capital letter, be sure you use the identical name when you call the function. Now, about those parentheses. The current Greet function always does the same thing: Each time you use it, it displays the same message. To make your function more flexible, you can add parameters, also known as argu- ments.
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. Here is the modified Greet function: Listing 7. However, if you load Listing 7. Making use of a function is referred to as calling the function.
This value will be assigned to the who variable inside the function. Functions can have more than one parameter. To define a function with multiple By the parameters, list a variable name for each parameter, separated by commas.
This allows you to use functions to cal- culate values. As an example, you can create a function that averages four numbers. 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: This is a By the common style, but you can also place the brace on the next line, or on a line by Way itself. Next, the function needs to calculate the average of the four parameters.
For example, in Chapter 5, you learned that the location. The href property is one of the properties of the location object in the DOM. The following example sends the browser to a new URL by changing the location. This is referred to as a child By the object. Way Understanding Methods Along with properties, each object can have one or more methods.
Arrays would improve things 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, but still not perfect.
Using Functions and Objects With objects, you can make the variables that store the database as logical as busi- ness cards. Each person is represented by a Card object, which has properties for name, address, and phone number.
You can even add methods to the object to dis- play or work with the information. Defining an Object The first step in creating an object is to name it and its properties.
Each object will have the following properties: This function is called the constructor for an object.
Here is the constructor function for the Card object: This function accepts sever- al parameters from the statement that calls the function, and then assigns them as properties of an object. Because the function is called Card, the object is the Card object. Notice the this keyword. Use this to refer to the current object—the one that is being created by the function. Defining an Object Method Next, you will 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 out the properties in a neat format. Here is a function definition for the PrintCard function: The last thing you need to do is make PrintCard part of the function definition for Card objects.
Here is the modified function definition: This will work so long as the PrintCard function is defined with its own function definition.
Methods are essentially properties that define a function rather than a simple value. The previous example uses lowercase names such as workphone for properties, Did you and an uppercase name PrintCard for the method.
You can use any case for Know? To use an object def- inition, you create a new object. This is done with the new keyword. The following statement creates a new Card object called tom: Using Functions and Objects As you can see, creating an object is easy.
This might be very useful if you were creating a large script that used many strings. You can add both properties and methods to an existing object by using the proto- type keyword.
The prototype keyword enables you to change the definition of an object outside its constructor function. You will create a method called heading, which converts a string into an HTML heading.
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 will need 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 out in the body of the document. PrintCard ; phred. PrintCard ; henry. PrintCard ; Notice that the PrintCard function has been modified slightly to make things look good with the captions in boldface.
Otherwise, it does nothing.
If you use an if statement like the preceding example, you can use a single state- ment as the action. If it finds a value of 1, it displays a message and sets a back to 0. This is called a conditional expression. A conditional expression usually includes two values to be compared in the preced- ing example, the values were a and 1. These values can be variables, constants, or even expressions in themselves.
The if Statement Either side of the conditional expression can be a variable, a constant, or an By the expression. You can compare a variable and a value, or compare two variables.
Between the two values to be compared is a conditional operator. The Pragmatic Programmer, From Journeyman To Master - Andrew Hunt, David Thomas - Addison Wesley - Straight from the programming trenches, The Pragmatic Programmer cuts through the increasing specialization and technicalities of modern software development to examine the core process--taking a requirement and producing working, maintainable code that delights its users.
It covers topics ranging from personal responsibility and career development to architectural techniques for keeping your code flexible and easy to adapt and reuse. Written as a series of self-contained sections and filled with entertaining anecdotes, thoughtful examples, and interesting analogies, The Pragmatic Programmer illustrates the best practices and major pitfalls of many different aspects of software development.
Martin Series Legacy code. The phrase strikes disgust in the hearts of programmers. It conjures images of slogging through a murky swamp of tangled undergrowth with leaches beneath and stinging flies above. It conjures odors of murk, slime, stagnancy, and offal. Click the link to view the print-fidelity code image. To return to the previous page viewed, click the Back button on your device or app. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher.
No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. Cover Designer Mark Shirar Compositor Bronkella Publishing Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized.
Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.
Special Sales For information about downloading this title in bulk quantities, or for special sales opportunities which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests , please contact our corporate sales department at corpsales pearsoned.
For government sales inquiries, please contact governmentsales pearsoned. For questions about sales outside the U. Table of Contents Introduction Part I: Objects HOUR 8: HOUR Exercises HOUR Using Libraries Why Use a Library?
Following an early career as a research scientist with a major multinational, he spent a few years in commercial and managerial roles within the high technology sector, later working full time as a software engineering consultant. We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We welcome your comments.
The code examples should work correctly in virtually any recent web browser. For the most part. Answers to the quiz items are conveniently provided immediately following the quiz. Caution Avoid common pitfalls by using the information in these blocks.
Try it Yourself Each hour contains at least one section that walks you through the process of implementing your own script. In addition to the main text of each lesson. Note These sections provide additional comments that might help you to understand the text and examples. Tip These blocks give additional hints. More sophisticated programming paradigms such as program control loops and timers are also covered.
Note Appendix A. To see your program code working. The examples in this book can all be created in a text-editing program. Nearly all hosts do. Simply storing the source code file in a convenient location on your computer and opening it with your chosen browser is generally sufficient. At least one such application ships with just about every operating system. It is recommended that you upgrade your browser to the latest current stable version. Check that your web host allows you to run scripts written in the PHP language if you want to try out the Ajax examples in Part V.
The exceptions to this are the hour on cookies and the examples in the book that demonstrate Ajax. Mozilla Firefox. Hour 1. The markup they contain will always be interpreted and displayed in the same way whenever the page is visited by a user.
Modern web pages can involve audio. Once written. The many functions such scripts can perform include animating page sections. Versus Client-Side Programming There are two fundamental ways of adding scripts to otherwise static web content: You can have the web server execute a script before delivering your page to the user.
These scripts are generally run at the web server before generating the requested web page and serving it to the user. We look at this in Part V.
The two languages share some aspects of syntax.
Right at the top of the hierarchical tree is the browser window object. Each object also has a list of properties that describe it.
The window object has various child objects. Any HTML page loaded into the browser creates a document object containing all of the HTML and other resources that go into making up the displayed page. All of these offer excellent support for the DOM. Apple Safari.
The first child object shown in Figure 1. Note The use of early browsers such as Netscape Navigator any version and Internet Explorer up to version 5. The window and document Objects Each time your browser loads and displays a page. These objects. In the DOM. This object is a parent or ancestor to everything else in the DOM representation of your page.
We look in detail at these objects in Hour 4. We can simply use window.. For example object1.
Object Notation The notation we use to represent objects within the tree uses the dot or period: Tip The window object always contains the current browser window. As a shortcut. We begin with two methods. The window object. Here we are calling the alert method of the window object. If you have several windows open. Tip In practice. To refer to one of these documents. When you call the alert method. So Click here to view code image.
Notice that the line of text inside the parentheses is contained within quotation marks. Tip Until the user clicks OK. The appearance of the dialog changes in detail depending on the particular browser.
Caution The default security settings in some browsers cause them to show a security warning when they are asked to open local content. Caution Some text editor programs might try to add a.
Save it to a convenient place on your computer. Be sure your saved file has the extension. Reading a Property of the document Object.. Notice that document. The result is shown in Figure 1. Without the quote marks. Edit hello.
In fact. Be careful—property names are case sensitive. The window object is at the top of the DOM tree. The window object Answers 1. Note the capital M.
Click here to view code image this is statement 1. We refer to such lines as comments. To add a multiline comment in this way. A comment that occupies just a single line of code can be written by placing a double forward slash before the content of the line: Comments can act as reminders to you.
When the user clicks on the button. This convention has arisen because. Replacing onmouseover with onmouseout in the code will. The onMouseOut event.
When using this within an event handler added via an attribute of an HTML element. Creating an Image Rollover We can use the onMouseOver and onMouseOut events to change how an image appears while the mouse pointer is above it. The code is shown in Listing 2. You can change the image names tick.
You should see that the image changes as the mouse pointer enters. In this example we used two images.
Their names are case sensitive. They can contain numeric or non-numeric information. Their names may contain spaces. Answers 1. An onClick event handler is a script that executes when the user clicks the mouse.
Instead, it waits quietly until the function is called. To call a function, you simply use the function name with the parentheses wherever you want to execute the statements contained in the function: For example, you may want to add a call to your new function sayHello to the onClick event of a button: Tip Function names, like variable names, are case-sensitive.
Fortunately, you can extend the capabilities of functions a great deal by passing data to them. You do this when the function is called, by passing to it one or more arguments: Now we can call our function, replacing the variable x with a number. Calling the function like the following results in a dialog box being displayed that contains the result of the calculation, in this case Of course, you could equally pass a variable name as an argument.
The following code would also generate a dialog containing the number Multiple Arguments Functions are not limited to a single argument.