JavaScript in Easy Steps 6th Edition 9781840788778 TOCCh1
JavaScript in Easy Steps 6th Edition 9781840788778 TOCCh1
Index 187
How to Use This Book
The examples in this book demonstrate JavaScript features that are supported by modern web
browsers, and the screenshots illustrate the actual results produced by the listed code examples.
Certain colorization conventions are used to clarify the code listed in the steps...
JavaScript code is colored blue, programmer-specified names are colored red, literal text is
colored black, and code comments are colored green:
let sum = ( 9 + 12 ) / 3 // Equivalent to 21 / 3.
document.getElementById( ‘info’ ).innerHTML += ‘Grouped sum: ‘ + sum
HTML tags are colored blue, literal text is colored black, and element attribute values are colored
orange in both HTML and JavaScript code:
Additionally, in order to identify each source code file described in the steps, a file icon and file
name appears in the margin alongside the steps:
JS JSON
{}
page.html external.js data.json data.xml echo.pl banner.svg
The source code of HTML documents used in the book’s examples is not listed in full to avoid
unnecessary repetition, but the listed HTML code is the entire fragment of the document
to which the listed JavaScript code is applied. You can download a single ZIP archive file
containing all the complete example files by following these easy steps:
l 2 Next, find JavaScript in easy steps, 6th edition in the list, then click on the hyperlink
entitled All Code Examples to download the ZIP archive file
l 3 Now, extract the archive contents to any convenient location on your computer
If you don’t achieve the result illustrated in any example, simply compare your code to that in
the original example files you have downloaded to discover where you went wrong.
Get Started
1 in JavaScript
Meet JS
JavaScript (“JS”) is an object-based scripting language whose
interpreter is embedded inside web browser software such as
Google Chrome, Microsoft Edge, Firefox, Opera, and Safari.
This allows scripts contained in a web page to be interpreted
when the page is loaded in the browser to provide functionality.
For security reasons, JavaScript cannot read or write files, with the
exception of “cookie” files that store minimal data.
Created by Brendan Eich at Netscape, JavaScript was first
introduced in December 1995, and was initially named
“LiveScript”. It was soon renamed, however, to perhaps capitalize
on the popularity of Sun Microsystem’s Java programming
language – although it bears little resemblance.
Before the introduction of JavaScript, web page functionality
required the browser to call upon “server-side” scripts, resident on
the web server, where slow response could impede performance.
Calling upon “client-side” scripts resident on the user’s system,
overcame the latency problem and provided a superior experience.
JavaScript quickly became very popular but a disagreement
8
<script>
document.getElementById( ‘message’ ).innerText = ‘Hello World!’
</script> You may see a
type=”text/javascript”
An HTML document can include multiple scripts, and these attribute in a <script>
may be placed in the head or body section of the document. It is, tag but this is no longer
however, recommended that you place scripts at the end of the required as JavaScript is
body section (immediately before the </body> closing tag) so the now the default scripting
browser can render the web page before interpreting the script. language for HTML.
9
Do not include <script>
document, and the browser will treat the script as though it was
and </script> tags in an
written directly at that position in the HTML document. external JavaScript file,
Assigning only the file name of an external script to the src only the script code.
attribute of a <script> tag requires the script file to be located in
the same folder (directory) as the HTML document. If the script
is located in an adjacent folder you can assign the relative path
address of the file instead, like this:
If the script is located elsewhere, you can assign the absolute path
address of the file, like this:
<script src=”https://www.example.com/js/external_script.js”>
</script> External script files can
make code maintenance
You can also specify content that will only appear in the web easier but almost all
page if the user has disabled JavaScript in their web browser examples in this book are
by including a <noscript> element in the body of the HTML standalone for clarity, so
document, like this: include the script code
between tags directly in
<noscript>JavaScript is Not Enabled!</noscript> the HTML document.
Get Started in JavaScript
Console Output
JavaScript can display output by dynamically writing content into
an HTML element. For example, with this code:
document.getElementById( ‘message’ ).innerText = ‘Hello World!’
This calls the alert( ) method of the window object to display the
10
l 3 Next, hit the F12 key, or use your browser’s menu to open
its Developers Tools feature
11
See that the console
displays the output plus
the name of the HTML
document and the line
number upon which the
JavaScript code appears
that created the output.
Make Statements
JavaScript code is composed of a series of instructions called
“statements”, which are generally executed in top-to-bottom order
as the browser’s JavaScript engine proceeds through the script.
Each statement may contain any of the following components:
• Keywords
The JavaScript keywords
are described on pages – words that have special significance in the
14-15 and you will learn JavaScript language.
• Operators
about operators, values,
and expressions later.
– special characters that perform an operation on
one or more operands.
• Values – text
, and
undefined
strings, numbers, Boolean
.
null
trueor ,
false
13
single value of 100:
( 80 + 20 )
Avoid Keywords
In JavaScript code you can choose your own names for variables
and functions. The names should be meaningful and reflect the
purpose of the variable or function. Your names may comprise
letters, numbers, and underscore characters, but they may not
contain spaces or begin with a number. You must also avoid these
words of special significance in the JavaScript language:
JavaScript Keywords
15
pageXOffset pageYOffset parent parseFloat
parseInt password pkcs11 plugin
prompt propertyIsEnum radio reset
screenX screenY scroll secure
select self setInterval setTimeout
status submit taint text
textarea top unescape untaint
window
Store Values
A “variable” is a container, common to every scripting and
programming language, in which data can be stored and
retrieved later. Unlike the “strongly typed” variables in most other
languages, which must declare a particular data type they may
contain, JavaScript variables are much easier to use because they
are “loosely typed” – so they may contain any type of data:
17
console.log( ‘jsSymbol: ‘ + typeof jsSymbol ) operator is used here to
console.log( ‘emptyVariable: ‘ + typeof emptyVariable ) output a combined text
console.log( ‘unusedVariable: ‘ + typeof unusedVariable ) string.
Create Functions
A function expression is simply one, or more, statements that
are grouped together in { } curly brackets for execution, and it
returns a final single value. Functions may be called as required by
a script to execute their statements. Those functions that belong
to an object, such as console.log( ), are known as “methods” – to
differentiate them from built-in and user-defined functions. Both
have trailing parentheses that may accept “argument” values to
be passed to the function for manipulation – for example, an
argument passed in the parentheses of the console.log( ) method.
The number of arguments passed to a function must normally
match the number of “parameters” specified within the parentheses
of the function block declaration. For example, a user-defined
function requiring exactly one argument looks like this:
Notice that the preferred function function-name ( parameter ) {
format of a function // Statements to be executed go here.
}
declaration places the
{ opening curly bracket
Multiple parameters can be specified as a comma-separated list
on the same line as the
and you can, optionally, specify a default value to be used when
function keyword.
18
return result
}
19
console.log( ‘8 + 20: ‘ + add( 8, 20 ) )
only one argument value
console.log( ‘8 + 10: ‘ + add( 8 ) ) is passed by the caller.
console.log( ‘(8 x 8) + (8 + 10): ‘ + squareAdd( 8 ) )
Assign Functions
Functions are really useful in JavaScript as they can be called
(“invoked”) to execute their statements whenever required, and the
caller can pass different arguments to return different results.
It is important to recognize that the JavaScript ( ) parentheses
When assigning a named operator is the component of the call statement that actually calls
function to a variable, the function. This means a statement can assign a function to a
only specify the function variable by specifying just the function name. The variable can
name in the statement. then be used to call the function in a statement that specifies
the variable name followed by the ( ) operator. But beware, if
you attempt to assign a function to a variable by specifying the
function name followed by ( ) the function will be invoked and
the value returned by that function will be assigned.
Function Hoisting
Although scripts are read by the JavaScript interpreter in top-
to-bottom order it actually makes two sweeps. The first sweep
looks for function declarations and remembers any it finds in a
Variables that were
process known as “hoisting”. The second sweep is when the script
declared using the is actually executed by the interpreter. Hoisting allows function
20
older var keyword were calls to appear in the script before the function declaration, as the
also hoisted, but those interpreter has already recognized the function on the first sweep.
declared with let or The first sweep does not, however, recognize functions that have
const are not hoisted. been assigned to variables using the let or const keywords!
Anonymous Functions
When assigning a function to a variable, a function name can be
omitted as the function can be called in a statement specifying the
variable name and the ( ) operator. These are called anonymous
function expressions, and their syntax looks like this:
let variable = function ( parameters ) { statements ; return value }
21
l 5 Finally, assign the value returned from a self-invoking
function to a variable and display that value
let iffy = ( function ( ) {
The significance of
self-invoking functions
may not be immediately
obvious, but their
let str = ‘Self Invoked Output’ ; return str importance should
})()
become clearer by the
console.log( iffy )
end of this chapter.
Recognize Scope
The extent to which variables are accessible in your scripts is
determined by their “lexical scope” – the environment in which
the variable was created. This can be either “global” or “local”.
Global Scope
Variables created outside function blocks are accessible globally
throughout the entire script. This means they exist continuously
and are available to functions within the same script environment.
At first glance this might seem very convenient, but it has a very
serious drawback in that variables of the same name can conflict.
For example, imagine that you have created a global myName
variable that has been assigned your name, but then also include
an external script in which another developer has created a global
myName variable that has been assigned his or her name. Both
like-named variables exist in the same script environment, so
conflict. This is best avoided so you should not create global
variables to store primitive values (all data types except Object
and Function) within your scripts.
Local Scope
22
Best Practice
Declaring global variables with the older var keyword allows
like-named conflicting variables to overwrite their assigned
You will discover how values without warning. The more recent let and const keywords
to catch errors on prohibit this and instead recognize the behavior as an “Uncaught
pages 60-61.
SyntaxError”. It is therefore recommended that you create
variables declared using the let or const keywords to store values
within your scripts.
...cont’d
l 3 Save both files in the same folder, then open the HTML
document to see a conflict error reported in the console
23
l 4 Edit both scripts to make the global variables into local
variables then refresh the browser to see no conflict
function readName( ) {
let myName = ‘External Script’ ; console.log( myName )
}
The function calls
function getName( ) { readName( ) and
let myName = ‘Internal Script’ ; console.log( myName ) getName( ) remain in the
} scripts without editing.
Get Started in JavaScript
Use Closures
The previous example demonstrated the danger of creating global
variables to store values in JavaScript, but sometimes you will
want to store values that remain continuously accessible – for
example, to remember an increasing score count as the script
proceeds. How can you do this without using global variables to
store primitive values? The answer lies with the use of “closures”.
A closure is a function nested inside an outer function that retains
access to variables declared in the outer function – because that is
the lexical scope in which the nested function was created.
Self-invoking function
expressions are described
on page 20. They
l 4 Finally, add three identical function calls to the inner
function that is now assigned to the global variable
console.log( ‘Count is ‘ + add( ) )
execute their statements console.log( ‘Count is ‘ + add( ) )
one time only. Here, console.log( ‘Count is ‘ + add( ) )
you can use
console.log( add ) to
confirm that the function
expression has been
l 5 Save the HTML document, then open it in your browser
and launch the console to see values returned from a closure
assigned to the outer
variable.
...cont’d
l
All JavaScript objects
6 Add a statement at the end of the script to reveal how inherit properties
and methods from a
the assigned function has been constructed internally
prototype. Standard
console.log( add.prototype )
JavaScript objects, such
l
as functions, call an
7 Save the HTML document, then refresh the browser and internal constructor
expand the “constructor” drop-down to see the scopes function to create the
object by defining its
components.
25
Closer inspection reveals that the assigned function has a special
(Closure) scope in addition to the regular local (Script) scope Don’t worry if you can’t
and outer (Global) scope. This is how the count variable remains immediately understand
accessible via the assigned function yet, importantly, cannot be how closures work. They
referenced in any other way. can seem mystical at
first, but will become
The use of closures to hide persistent variables from other parts of clearer with experience.
your script is an important concept. It is similar to how “private” You can continue on
variables can be hidden in other programming languages and are and come back to this
only accessible via “getter” methods. technique later.
Get Started in JavaScript
Summary
• JavaScript code can be included in an HTML document
directly or from an external file using tags.
<script> </script>
• new
Variables declared with the
values, but the const
let keyword can be reassigned
keyword does not allow this.
26
• brackets
A function expression has statements grouped in {}curly
for execution, and it returns a final single value.
• parameters
The parentheses of a function expression may contain
()
for argument values to be passed from the caller.
• Aretains
closure is a function nested within an outer function that
access to variables declared in the outer function.