Professional Documents
Culture Documents
Javascript A Beginners Guide Fifth Edition John Pollock Full Chapter
Javascript A Beginners Guide Fifth Edition John Pollock Full Chapter
ISBN: 978-1-26-045769-8
MHID: 1-26-045769-9
The material in this eBook also appears in the print version of this
title: ISBN: 978-1-26-045768-1, MHID: 1-26-045768-0.
TERMS OF USE
1 Introduction to JavaScript
What You Need to Know
Basic HTML and CSS Knowledge
Basic Text Editor and Web Browser Knowledge
Which Version?
Client-Side and Server-Side Programming
Beginning with JavaScript
Prototype-Based
Interpreted Language
Numerous Environments
Putting It All Together
Online Resources
Try This 1-1: Use JavaScript to Write Text
Chapter 1 Self Test
3 Using Variables
Understanding Variables
Why Variables Are Useful
Variables as Placeholders for Unknown Values
Variables as Time-Savers
Variables as Code Clarifiers
Defining Variables for Your Scripts
Declaring Variables
Assigning Values to Variables
Naming Variables
Understanding Data Types
Number
String
Boolean
Null
Undefined
Symbol
Object
Try This 3-1: Declare Variables
Using Variables in Scripts
Making a Call to a Variable
Adding Variables to Text Strings
Writing a Page of JavaScript
Creating the Framework
Defining the Variables
Adding the Commands
Modifying the Page
Try This 3-2: Create an HTML Page with JavaScript
Chapter 3 Self Test
4 Using Functions
What a Function Is
Why Functions Are Useful
Structuring Functions
Declaring Functions
Defining the Code for Functions
Naming Functions
Adding Arguments to Functions
Adding Return Statements to Functions
Calling Functions in Your Scripts
Script Tags: Head Section or Body Section
Calling a Function from Another Function
Calling Functions with Arguments
Calling Functions with Return Statements
Other Ways to Define Functions
Try This 4-1: Create an HTML Page with Functions
Scope/Context Basics
Global Context
Function Context
Block Context
Try This 4-2: Write Your Own Functions
Chapter 4 Self Test
5 JavaScript Operators
Understanding the Operator Types
Understanding Arithmetic Operators
The Addition Operator (+)
The Subtraction Operator (–)
The Multiplication Operator (*)
The Division Operator (/)
The Modulus Operator (%)
The Increment Operator (++)
The Decrement Operator (– –)
The Unary Plus Operator (+)
The Unary Negation Operator (–)
The Exponentiation Operator
Understanding Assignment Operators
The Assignment Operator (=)
The Add-and-Assign Operator (+=)
The Subtract-and-Assign Operator (–=)
The Multiply-and-Assign Operator (*=)
The Divide-and-Assign Operator (/=)
The Modulus-and-Assign Operator (%=)
The Exponent-and-Assign Operator (**=)
Try This 5-1: Adjust a Variable Value
Understanding Comparison Operators
The Is-Equal-To Operator (==)
The Is-Not-Equal-To Operator (!=)
The Strict Is-Equal-To Operator (===)
The Strict Is-Not-Equal-To Operator (!==)
The Is-Greater-Than Operator (>)
The Is-Less-Than Operator (<)
The Is-Greater-Than-or-Equal-To Operator (>=)
The Is-Less-Than-or-Equal-To Operator (<=)
Understanding Logical Operators
The AND Operator (&&)
The OR Operator (||)
The NOT Operator (!)
The Bitwise Operators
Special Operators
Understanding Order of Operations
Try This 5-2: True or False?
Chapter 5 Self Test
7 JavaScript Arrays
What Is an Array?
Why Arrays Are Useful
Defining and Accessing Arrays
Naming an Array
Defining an Array
Accessing an Array’s Elements
Using the length Property and Loops
Changing Array Values and Changing the Length
Try This 7-1: Use Loops with Arrays
Array Properties and Methods
Properties
Methods
Nesting Arrays
Defining Nested Arrays
Loops and Nested Arrays
Try This 7-2: Nested Arrays Practice
Chapter 7 Self Test
8 Objects
Defining Objects
Creating Objects
Naming
Single Objects
Try This 8-1: Create a Computer Object
Object Structures
Constructor Functions
Using Prototypes
The class Keyword
Helpful Statements for Objects
The for-in Loop
The with Statement
Try This 8-2: Practice with the Combination
Constructor/Prototype Pattern
Understanding Predefined JavaScript Objects
The Navigator Object
The History Object
Chapter 8 Self Test
9 The Document Object
Defining the Document Object
Using the Document Object Model
Using the Properties of the Document Object
Collections
The cookie Property
The dir Property
The lastModified Property
The referrer Property
The title Property
The URL Property
The URLUnencoded Property
Using the Methods of the Document Object
The get Methods for Elements
The open() and close() Methods
The write() and writeln() Methods
Using DOM Nodes
DOM Node Properties
DOM Node Methods
Try This 9-1: Add a DOM Node to the Document
Creating Dynamic Scripts
Styles in JavaScript
Simple Event Handling
Coding a Dynamic Script
Try This 9-2: Try Out Property Changes
Chapter 9 Self Test
10 Event Handlers
What Is an Event Handler?
Why Event Handlers Are Useful
Understanding Event Handler Locations and Uses
Using an Event Handler in an HTML Element
Using an Event Handler in the Script Code
Learning the Events
The Click Event
Focus and Blur Events
The Load and Unload Events
The Reset and Submit Events
The Mouse Events
The Keyboard Events
Try This 10-1: Focus and Blur
Other Ways to Register Events
The addEventListener() Method
The attachEvent() Method
The Event Object
DOM and Internet Explorer: DOM Level 0 Registration
Using event with Modern Event Registration
Properties and Methods
Event Information
Try This 10-2: Using addEventListener()
Creating Scripts Using Event Handlers
Show Hidden Content
Change Content
Custom Events
Chapter 10 Self Test
11 Introduction to Node.js
Introducing Node.js
Installing Node.js
Check for a Current Installation
Install Node.js
Write a “Hello World” Script
Using Node Modules
Using Native Node Modules
Asynchronous Execution
Non-Native Modules
Try This 11-1: Use a Custom Module
Installing a Database
Database Options
Install PostgreSQL
Create a Database Using pgAdmin
Try This 11-2: Test Some SQL Queries
Creating a Web Server
Chapter 11 Self Test
13 Handling Strings
Introduction to the String Object
The String Object
The String Literal
What’s the Difference?
Using the Properties and Methods of the String Object
The length Property
Methods of the String Object
Try This 13-1: Use indexOf() to Test an Address
Using Cookies
Setting a Cookie
Reading a Cookie
Try This 13-2: Remember a Name
Using Regular Expressions
Creating Regular Expressions
Testing Strings Against Regular Expressions
Adding Flags
Creating Powerful Patterns
Grouping Expressions
The replace(), match(), matchAll(), and search() Methods
More Information
Continuing Project
Chapter 13 Self Test
14 Browser-Based JavaScript
Window: The Global Object
Using the Properties of the Window Object
The closed Property
The frames Property
The innerWidth and innerHeight Properties
The length Property
The location Property
The name Property
The opener Property
The parent, self, and top Properties
The status and defaultStatus Properties
Try This 14-1: Use the location and innerWidth Properties
Using the Methods of the Window Object
The alert(), prompt(), and confirm() Methods
The print() Method
The setInterval() and clearInterval() Methods
The setTimeout() and clearTimeout() Methods
Try This 14-2: Use the setTimeout() and confirm() Methods
The Main Window and New Windows
The Tale of Pop-up Windows
Opening New Windows
Closing New Windows
Moving, Resizing, and Scrolling New Windows
The resizeBy() and resizeTo() Methods
The scrollBy() and ScrollTo() Methods
Working with Images
Rollovers
JavaScript and Frames
Purpose of Frames
Accessing Frames
Breaking Out of Frames
Using iFrames
Chapter 14 Self Test
Index
Acknowledgments
• Key Skills & Concepts Each chapter begins with a set of key
skills and concepts that you will understand by the end of the
chapter.
• Ask the Expert The Ask the Expert sections present commonly
asked questions about topics covered in the preceding text, with
responses from the author.
• Try This These sections get you to practice what you have
learned using a hands-on approach. Each Try This will have you
code a script through step-by-step directions on what you need to
do to in order to accomplish the goal. You can find solutions to
each project on the McGraw-Hill Professional Web site at
www.mhprofessional.com/computingdownload.
• Notes, Tips, and Cautions These elements call your attention
to noteworthy statements that you will find helpful as you move
through the chapters.
• Code Code listings display example source code used in scripts
or programs.
• Callouts Callouts display helpful hints and notes about the
example code, pointing to the relevant lines in the code.
• Self Test Each chapter ends with a Self Test, a series of 15
questions to see if you have mastered the topics covered in the
chapter. The answers to each Self Test can be found in the
appendix.
That is it! You are now familiar with the organization and special
features of this book to start your journey through JavaScript. If you
find that you are stuck and need help, feel free to contact me with
your questions. To contact me, you can reach me on LinkedIn
(https://www.linkedin.com/in/john-pollock-82a2b074) or you can
find me on Twitter (@ScripttheWeb).
Now it is time to learn JavaScript. Get ready, get set, and have
fun!
Chapter 1
Introduction to JavaScript
If you have this basic knowledge, you’ll do just fine as you work through
this book. Knowing another programming/scripting language or having
previous experience with JavaScript isn’t required. This book is a beginner’s
guide to JavaScript.
If you think you don’t have enough experience in one of the
aforementioned areas, a closer look at each one may help you decide what
to do.
If you know the basics of using tags and attributes, the HTML portion
shouldn’t pose any problems in learning JavaScript.
If you don’t have a basic knowledge of HTML, you can learn it fairly
quickly through a number of media. For example, you can buy a book or
look for some helpful information on the Web. A good book is HTML: A
Beginner’s Guide, Fifth Edition by Wendy Willard (McGraw-Hill, 2013). To
find information about HTML on the Web, check out
developer.mozilla.org/en-
US/docs/Learn/HTML/Introduction_to_HTML/Getting_started.
Occasionally, you will need to use CSS to add or change presentation
features on a Web page. We will mainly use CSS for the purposes of
dynamically changing CSS properties via JavaScript in this book. A good
place to learn CSS is developer.mozilla.org/en-
US/docs/Learn/CSS/Introduction_to_CSS/How_CSS_works.
Text Editors
A number of text editors and HTML editors support JavaScript. If you know
HTML, you’ve probably already used an HTML editor to create your HTML
files, so you might not have to change.
However, some HTML editors have problems related to adding
JavaScript code (such as changing where the code is placed or altering the
code itself when you save the file). This is more often the case when using
WYSIWYG (What You See Is What You Get) editors. It is best to use a code
editor such as Sublime or Visual Studio Code (recommended) or a plain
text editor. Some examples of text editors are Notepad, TextPad, and
Simple Text.
Web Browsers
Again, if you’ve been coding in HTML, you probably won’t need to change
your browser. However, some browsers have trouble with the newer
versions of JavaScript. The choice of Web browser is ultimately up to you,
as long as it’s compatible with JavaScript. I recommend the latest version
of one of following browsers to test your JavaScript code:
• Google Chrome
• Mozilla Firefox
• Microsoft Edge
Au matin
Au matin avec le tombereau noir…
Nous remonterons à Vine street, au matin !
— C’est à Bow street que vous allez venir, vous, dit l’agent avec
aigreur.
— Cet homme est mourant. (Il geignait, étendu sur le pavé.)
Amenez l’ambulance, dis-je.
Il y a une ambulance derrière St. Clément Danes, ce en quoi je
suis mieux renseigné que beaucoup. L’agent, paraît-il, possédait les
clefs du kiosque où elle gîtait. Nous la sortîmes (c’était un engin à
trois roues, pourvu d’une capote) et nous jetâmes dessus le corps
de l’individu.
Placé dans une voiture d’ambulance, un corps a l’air aussi mort
que possible. A la vue des semelles de bottes roides, les agents se
radoucirent.
— Allons-y donc, firent-ils.
Je m’imaginai qu’ils parlaient toujours de Bow street.
— Laissez-moi voir Dempsey trois minutes, s’il est de service,
répliquai-je.
— Entendu. Il y est.
Je compris alors que tout irait bien, mais avant de nous mettre en
route, je passai la tête sous la capote de l’ambulance, pour voir si
l’individu était encore en vie. Mon oreille perçut un chuchotement
discret.
— Petit gars, tu devras me payer un nouveau chapeau. Ils m’ont
crevé le mien. Ne va pas me lâcher à cette heure, petit gars. Avec
mes cheveux gris je suis trop vieux pour aller en prison par ta faute.
Ne me lâche pas, petit gars.
— Vous aurez de la chance si vous vous en tirez à moins de sept
ans, dis-je à l’agent.
Mûs par une crainte très vive d’avoir outrepassé leur devoir, les
deux agents quittèrent leurs secteurs de surveillance, et le lugubre
convoi se déroula le long du Strand désert. Je savais qu’une fois
arrivé à l’ouest d’Adelphi je serais en pays ami. Les agents
également eurent sujet de le savoir, car tandis que je marchais
fièrement à quelques pas en avant du catafalque, un autre agent me
jeta au passage :
— Bonsoir, monsieur.
— Là, vous voyez, dis-je avec hauteur. Je ne voudrais pour rien
au monde être dans votre peau. Ma parole, j’ai bonne envie de vous
mener tous deux à la préfecture de police.
— Si ce monsieur est de vos amis, peut-être… dit l’agent qui
avait asséné le coup et songeait aux conséquences de son acte.
— Peut-être aimeriez-vous me voir partir sans rien dire de
l’aventure, complétai-je.
Alors apparut à nos yeux la silhouette du brigadier Dempsey, que
son imperméable rendait pour moi pareil à un ange de lumière. Je le
connaissais depuis des mois, il était de mes meilleurs amis, et il
nous arrivait de bavarder ensemble dans le petit matin. Les sots
cherchent à gagner les bonnes grâces des princes et des ministres,
et les cours et ministères les laissent périr misérablement. Le sage
se fait des alliés parmi la police et les cochers de fiacre, en sorte que
ses amis jaillissent du kiosque et de la file de voitures, et que ses
méfaits eux-mêmes se terminent en cortèges triomphaux.
— Dempsey, dis-je, y aurait-il eu une nouvelle grève dans la
police ? On a mis de faction à St. Clément Danes des êtres qui
veulent m’emmener à Bow street comme étrangleur.
— Mon Dieu, monsieur ! fit Dempsey, indigné.
— Dites-leur que je ne suis pas un étrangleur ni un voleur. Il est
tout bonnement honteux qu’un honnête homme ne puisse se
promener dans le Strand sans être malmené par ces rustres. L’un
d’eux a fait son possible pour tuer mon ami ici présent ; et j’emmène
le cadavre chez lui. Parlez en ma faveur, Dempsey.
Les agents dont je faisais ce triste portrait n’eurent pas le temps
de placer un mot. Dempsey les interpella en des termes bien faits
pour les effrayer. Ils voulurent se justifier, mais Dempsey entreprit
une énumération glorieuse de mes vertus, telles qu’elles lui étaient
apparues à la lumière du gaz dans les heures matinales.
— Et en outre, conclut-il avec véhémence, il écrit dans les
journaux. Hein, ça vous plairait, qu’il parle de vous dans les
journaux… et en vers, encore, selon son habitude. Laissez-le donc.
Voilà des mois que lui et moi nous sommes copains.
— Et le mort, qu’en fait-on ? dit l’agent qui n’avait pas asséné le
coup.
— Je vais vous le dire, répliquai-je, me radoucissant.
Et aux trois agents assemblés sous les lumières de Charing
Cross, je fis un récit fidèle et détaillé de mes aventures de la nuit, en
commençant par le Breslau et finissant à St. Clément Danes. Je leur
dépeignis le vieux gredin couché dans la voiture d’ambulance en des
termes qui firent se tortiller ce dernier, et depuis la création de la
police métropolitaine, jamais trois agents ne rirent comme ces trois-
là. Le Strand en retentit, et les louches oiseaux de nuit en restèrent
ébahis.
— Ah Dieu ! fit Dempsey en s’essuyant les yeux, j’aurais donné
gros pour voir ce vieux type galoper avec sa couverture mouillée et
le reste. Excusez-moi, monsieur, mais vous devriez vous faire
ramasser chaque nuit pour nous donner du bon temps.
Et il se répandit en nouveaux esclaffements.
Des pièces d’argent tintèrent, et les deux agents de St. Clément
Danes regagnèrent vivement leurs secteurs : ils riaient tout courants.
— Emmenez-le à Charing Cross, me dit Dempsey entre ses
éclats de rire. On renverra l’ambulance dans la matinée.
— Petit gars, tu m’as appelé de vilains noms, mais je suis trop
vieux pour aller à l’hôpital. Ne me lâche pas, petit gars. Emmène-moi
chez moi auprès de ma femme, dit la voix sortant de l’ambulance.
— Il n’est pas tellement malade. Sa femme lui flanquera un
fameux savon, dit Dempsey qui était marié.
— Où logez-vous ? demandai-je.
— A Brugglesmith, me fut-il répondu.
— Qu’est-ce que c’est que ça ? demandai-je à Dempsey, plus
versé que moi dans les mots composés de ce genre.
— Quartier de Brook Green, arrondissement d’Hammersmith,
traduisit aussitôt Dempsey.
— Évidemment, repris-je. Il ne pouvait pas loger ailleurs. Je
m’étonne seulement que ce ne soit pas à Kew [22] .
[22] Brook Green se trouve à l’extrême ouest de
Londres, à six kilomètres et demi de Charing Cross. Kew
est encore plus loin, dans la même direction.