0% found this document useful (0 votes)
18 views24 pages

JavaScript in Easy Steps 6th Edition 9781840788778 TOCCh1

The document serves as a comprehensive guide to JavaScript, covering fundamental concepts, operations, and practical applications. It includes chapters on script inclusion, managing script flow, using objects, and creating web applications, with detailed explanations and examples. The book also provides insights into JavaScript's history and its integration with HTML, as well as best practices for coding and debugging.

Uploaded by

Bsamsungb99 S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views24 pages

JavaScript in Easy Steps 6th Edition 9781840788778 TOCCh1

The document serves as a comprehensive guide to JavaScript, covering fundamental concepts, operations, and practical applications. It includes chapters on script inclusion, managing script flow, using objects, and creating web applications, with detailed explanations and examples. The book also provides insights into JavaScript's history and its integration with HTML, as well as best practices for coding and debugging.

Uploaded by

Bsamsungb99 S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Contents

1 Get Started in JavaScript 7


Meet JS 8
Include Scripts 9
Console Output 10
Make Statements 12
Avoid Keywords 14
Store Values 16
Create Functions 18
Assign Functions 20
Recognize Scope 22
Use Closures 24
Summary 26

2 Perform Useful Operations 27


Convert Values 28
Do Arithmetic 30
Assign Values 32
Make Comparisons 34
Assess Logic 36
Examine Conditions 38
Juggle Bits 40
Force Order 42
Summary 44

3 Manage the Script Flow 45


Branch If 46
Branch Alternatives 48
Switch Alternatives 50
Loop For 52
Loop While 54
Do Loops 56
Break Out 58
Catch Errors 60
Summary 62
4 Use Script Objects 63
Custom Objects 64
Extend Objects 66
Built-in Objects 68
Create Arrays 70
Loop Elements 72
Slice Arrays 74
Sort Elements 76
Get Dates 78
Extract Calendar 80
Extract Time 82
Set Dates 84
Match Patterns 86
Summary 88

5 Control Numbers & Strings 89


Calculate Areas 90
Compare Numbers 92
Round Decimals 94
Generate Randoms 96
Unite Strings 98
Split Strings 100
Find Characters 102
Trim Strings 104
Summary 106

6 Address the Window Object 107


Meet DOM 108
Inspect Properties 110
Show Dialogs 112
Scroll Around 114
Pop-up Windows 116
Make Timers 118
Examine Browsers 120
Check Status 122
Control Location 124
Travel History 126
Summary 128
7 Interact with the Document 129
Extract Info 130
Address Arrays 132
Address Elements 134
Write Content 136
Manage Cookies 138
Load Events 140
Mouse Events 142
Event Values 144
Check Boxes 146
Select Options 148
Reset Changes 150
Validate Forms 152
Summary 154

8 Create Web Applications 155


Meet JSON 156
Make Promises 158
Fetch Data 160
Create Interface 162
Fill Cells 164
Total Values 166
Update App 168
Summary 170

9 Produce Script Magic 171


Request Data 172
Embed Vectors 174
Paint Canvas 176
Store Data 178
Drag Items 180
Pass Messages 182
Locate Users 184
Summary 186

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:

<p id=”info”>JavaScript in easy steps</p>

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 1 Browse to www.ineasysteps.com then navigate to Free Resources and choose the


Downloads section

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

This chapter is an 8 Meet JS


introduction to the exciting 9 Include Scripts
world of JavaScript. It 10 Console Output
demonstrates how to add 12 Make Statements
scripts to HTML documents 14 Avoid Keywords
that provide JavaScript 16 Store Values
variables and functions. 18 Create Functions
20 Assign Functions
22 Recognize Scope
24 Use Closures
26 Summary
Get Started 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

arose between Netscape and Microsoft over its licensing – so


Microsoft introduced its own version named “JScript”. Although
similar to JavaScript, the new JScript version had some extended
features. Recognizing the danger of fragmentation, the JavaScript
language was standardized by the Ecma International standards
organization in June 1997 as “ECMAScript”. This helped to
stabilize core features but the name, sounding like some kind of
skin disease, is not widely used and most people will always call
Brendan Eich, creator of the language “JavaScript”.
the JavaScript language,
also co-founded the The JavaScript examples in this book describe three key ingredients:
Mozilla project and
helped launch the Firefox
web browser. • Language basics – illustrating the mechanics of the language
syntax, keywords, operators, structure, and built-in objects.

• Web page functionality – illustrating how to use the browser’s


Document Object Model (DOM) to provide user interaction.

• Web applications – illustrating responsive web-based apps


and JavaScript Object Notation ( JSON) techniques.
Include Scripts
To include JavaScript code directly in an HTML document it
must be inserted between <script> and </script> tags, like this:

<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.

JavaScript code can also be written in external plain text files


that are given a .js file extension. This allows several different web
pages to call upon the same script. In order to include an external
script in the HTML document, the file name of the script must
be assigned to a src attribute of the <script> tag, like this:
<script src=”external_script.js”> </script>

Again, this can be placed in the head or body section of the

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:

<script src=”js/external_script.js”> </script>

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!’

The element is identified by the value assigned to its id attribute


Notice the use of the
and the innerText property specifies text to be written there.
. period (full stop)
operator to describe
properties or methods
of an object using “dot
notation”.

Additionally, JavaScript can display output by writing content into


a pop-up dialog box, like this:
window.alert( ‘Hello World!’ )

This calls the alert( ) method of the window object to display the
10

There is also a content specified within the ( ) parentheses in a dialog box.


document.write( )
method that replaces
the entire header and
body of the web page,
but its use is generally
considered bad practice.

When developing in JavaScript, and learning the language, it


is initially better to display output in the browser’s JavaScript
console, like this:
console.log( ‘Hello World!’ )
The console provides
This calls the log( ) method of the console object to display the
helpful messages if an
error occurs in your
content specified within the ( ) parentheses in a console window.
code – so is great for All leading browsers have a JavaScript console within their
debugging the code. Developers Tools feature – typically accessed by pressing the F12
keyboard key. As the Google Chrome web browser is statistically
the most popular browser at the time of writing it is used
throughout this book to demonstrate JavaScript, and initially its
console window is used to display output.
...cont’d

l 1 Create an HTML document that includes an empty


paragraph and a script to display output in three ways
<p id=”message”></p>
<script>
document.getElementById( ‘message’ ).innerText = output.html
‘Hello World!’
window.alert( ‘Hello World!’ )
console.log( ‘Hello World!’ )
</script>

l 2 Save the HTML document then open it in your browser


to see the output written in the paragraph and displayed
in a dialog box – as illustrated opposite

l 3 Next, hit the F12 key, or use your browser’s menu to open
its Developers Tools feature

l 4 Now, select the Console tab to see the output written


into the console window

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.

l 5 Click the Show/Hide


button to hide or show the
sidebar, click the Customize
button to choose how the
console window docks in the
browser window, then click the
Clear button to clear all
content from the console
Get Started in JavaScript

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

• Expressions – units of code that produce a single value.


In earlier JavaScript code each statement had to be terminated by
a ; semicolon character – just as each sentence must end with a .
period (full stop) character in the English language. This is now
optional so may be omitted unless you wish to write multiple
statements on a single line. In that case, the statements do need to
12

An “expression” be separated by a semicolon, like this:


produces a value,
whereas a “statement” statement ; statement ; statement
performs an action.
Some JavaScript programmers still prefer to end each statement
with a semicolon. The examples in this book choose to omit them
for the sake of concision but the choice is yours.
The JavaScript interpreter ignores tabs and spaces (“whitespace”)
so you should use spacing to make your code more readable. For
example, when adding two numbers:
total = 100 + 200 rather than total=100+200
JavaScript statements are often grouped together within { } curly
brackets (“braces”) in function blocks that can be repeatedly called
to execute when required. It is good practice to indent those
statements by two spaces to improve readability, like this:
Use the space bar to
indent statements, as tab {
spacing may be treated statement
differently when viewing statement
the code in text editors. statement
}
...cont’d

The rules that govern the JavaScript language is called “syntax”,


and it recognizes two types of values – fixed and variable. Fixed
numeric and text string values are called “literals”:

• Number literals – whole number integers, such as


floating-point numbers such as .
3.142
, or
100
Decide on one form
of quotes to use in
• String literals –, text
“JavaScript Fun”
within either double quotes, such as
or single quotes such as .
‘JavaScript Fun’
your code for string
literals and stick with
it for consistency. The
Variable values are called, quite simply, “variables” and are used to examples in this book
store data within a script. They can be created using the JavaScript use single quotes.
let keyword – for example, let total creates a variable named
“total”. The variable can be assigned a value to store using the
JavaScript = assignment operator, like this:
let total = 300

Other JavaScript operators can be used to form expressions that


will evaluate to a single value. Typically, an expression may be
enclosed within ( ) parentheses like this expression that comprises
numbers and the JavaScript + addition operator and evaluates to a

13
single value of 100:
( 80 + 20 )

Expressions may also contain variable values too, like this


expression that comprises the previous variable value, the
JavaScript - subtraction operator, and a number, to also evaluate to
a single value of 100:
( total - 200 )

JavaScript is a case-sensitive language so variables named total


and Total are regarded as two entirely different variables.
It is good practice to add explanatory comments to your
JavaScript code to make it more easily understood by others, and
by yourself when revisiting the code later. Anything that appears
on a single line following // double slashes or between /* and */
character sequences on one or more lines will be ignored. It is often useful to
“comment-out” lines
let total = 100 // This code WILL be executed. of code to prevent
their execution when
/* let total = 100 debugging code.
This code will NOT be executed. */
Get Started in JavaScript

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

abstract arguments await boolean


break byte case catch
char class const continue
debugger default delete do
double else enum eval
export extends false final
finally float for function
goto if implements import
14

in instanceof int interface


let long native new
null package private protected
public return short static
super switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield

JavaScript Objects, Properties, and Methods

Array Date eval function


hasOwnProperty Infinity isFinite isNaN
isPrototypeOf length Math NaN
name Number Object prototype
String toString undefined valueOf
...cont’d

HTML Names, Window Objects, and Properties

alert all anchor anchors


area assign blur button
checkbox clearInterval clearTimeout clientInformation
close closed confirm constructor
crypto decodeURI decodeURIcomponent defaultStatus
document element elements embed
embeds encodeURI encodeURIcomponent escape
event fileUpload focus form
forms frame innerHeight innerWidth
layer layers link location
mimeTypes navigate navigator frames
frameRate hidden history image
images offscreenBuffering open opener
option outerHeight outerWidth packages

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

HTML Event Attributes


For Example:
onclick ondblclick onfocus onfocusout
onkeydown onkeypress onkeyup onload
onmousedown onmouseup onmouseover onmouseout
onmousemove onchange onreset onsubmit
Get Started in JavaScript

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:

Data Type Example Description

String ‘Hello World!’ A string of text characters


Number 3.142 An integer or floating-point number
A variable name is an Boolean true A true (1) or false (0) value
alias for the value it
Object console A user-defined or built-in object
contains – using the
name in script references Function log( )
A user-defined function, a built-in
its stored value. function, or an object method
Symbol Symbol( ) A unique property identifier
null null Absolutely nothing (not even zero)
16

undefined undefined A non-configured property

A JavaScript variable can be declared using the let, const, or


var keywords followed by a space and a name of your choosing.
Variables declared with let can be reassigned new values as the
script proceeds, whereas const (constant) does not allow this. The
var keyword was used in JavaScript before the let keyword was
Choose meaningful introduced but is best avoided now as it does not prevent you
names for your variables
declaring the same variable twice in the same context.
to make the script easier
to understand later. A let declaration of a variable in a script may simply create a
variable to which a value can be assigned later, or may include an
assignation to instantly “initialize” the variable with a value:
let myNumber // Declare a variable.
myNumber = 10 // Initialize a variable.
let myString = ‘Hello World!’ // Declare and initialize a variable.

Multiple variables may be declared on a single line too:


let i , j , k // Declare 3 variables.
let num =10 , char = ‘C’ // Declare and initialize 2 variables.

Constant variables must, however, be initialized when declared:


const myName = ‘Mike’
...cont’d

Upon initialization, JavaScript automatically sets the variable type


for the value assigned. Subsequent assignation of a different data
type later in the script can be made to change the variable type.
The current variable type can be revealed by the typeof keyword.

l 1 Create an HTML document with a script that declares


several variables that are assigned different data types
const firstName = ‘Mike’
const valueOfPi = 3.142
let isValid = true
variables.html
let jsObject = console
let jsMethod = console.log
let jsSymbol = Symbol( )
let emptyVariable = null
let unusedVariable

l 2 Add statements to output the data type of each variable


console.log(
console.log(
‘firstName: ‘ + typeof firstName )
‘valueOfPi: ‘ + typeof valueOfPi )
console.log( ‘isValid: ‘ + typeof isValid )
console.log( ‘jsObject: ‘ + typeof jsObject )
console.log( ‘jsMethod: ‘ + typeof jsMethod ) The concatenation +

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.

l 3 Save the HTML document then open it in your browser


and launch the console to see the data types in output

You should be surprised


to see that the variable
assigned a null value
is described as being
an object type, rather
than a null type. This
is a known error in the
JavaScript language.
Get Started in JavaScript

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

the function call does not pass an argument, like this:


function function-name ( parameter , parameter = value ) {
// Statements to be executed go here.
}

You choose your own parameter names following the same


naming conventions as for variable names. The parameter names
can then be used within the function to reference the argument
values passed from the parentheses of the function call.
You can omit the return A function block can include a return statement so that script
statement, or use the flow continues at the caller – no further statements in the
return keyword without function get executed. It is typical to finally return the result of
specifying a value, and manipulating passed argument values back to the caller:
the function will simply
return an undefined function function-name ( parameter , parameter ) {
value to the caller. // Statements to be executed go here.

return result
}

It is common for statements within a function block to include


calls to other functions – to modularize scripts into blocks.
...cont’d

l 1 Create an HTML document with a script that declares a


function to return the squared value of a passed argument
function square ( arg ) {
return arg * arg
} functions.html

l 2 Next, add a function that returns the result of an addition


function add ( argOne, argTwo = 10 ) {
return argOne + argTwo
}

l 3 Now, add a function that returns the result of squaring


and an addition by calling each of the functions above
function squareAdd ( arg ) {
let result = square( arg )
return result + add( arg )
}

l 4 Finally, add statements that call the functions and print


the returned values in output strings
console.log( ‘8 x 8: ‘ + square( 8 ) )
Notice that the default
second parameter value
(10) is used here when

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 ) )

l 5 Save the HTML document, then open it in your browser


and launch the console to see values returned from functions

The * asterisk character


is the arithmetical
multiplication operator in
JavaScript.
Get Started in JavaScript

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 }

Anonymous function expressions can also be made “self-invoking”


by enclosing the entire function within ( ) parentheses and adding
the ( ) parentheses operator at the end of the expression. This
Self-invoking function means that their statements are automatically executed one time
expressions are also when the script is first loaded by the browser. The syntax of a self-
known as Immediately invoking function expression looks like this:
Invoked Function
Expressions (IIFE – often ( function ( ) { statements ; return value } ) ()
pronounced “iffy”).
Self-invoking functions are used widely throughout this book to
execute example code when the script gets loaded.
...cont’d

l 1 Create an HTML document with a script that calls a


function that has not yet been declared
console.log( ‘Hoisted: ‘ + add( 100, 200 ) )

l 2 Next, add below the function that is called above


function add( numOne, numTwo ) {
return numOne + numTwo
anonymous.html

l 3 Now, add a function that assigns the function above to a


variable, then calls the assigned function
let addition = add
console.log( ‘Assigned: ‘ + addition( 32, 64 ) )

l 4 Then, assign a similar, but anonymous, function to a


variable and call that assigned function
let anon = function ( numOne, numTwo ) {
let result = numOne + numTwo ; return result
}
console.log( ‘Anonymous: ‘ + anon( 9, 1 ) )

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.

l 6 Save the HTML document, then open it in your browser


and launch the console to see values returned from functions
Get Started in JavaScript

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

Variables created inside function blocks are accessible locally


throughout the life of the function. They exist only while the
function is executing, then they are destroyed. Their script
environment is limited – from the point at which they are
created, to the final } curly bracket, or the moment when the
function returns. It is good practice to declare variables at the
very beginning of the function block so their lexical scope is the
duration of the function. This means that like-named variables can
exist within separate functions without conflict. For example, a
local myName variable can exist happily inside separate functions
within your script and inside functions in included external
scripts. It is recommended that you try to create only local
variables to store values within your scripts.

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 1 Create an external script that calls a function to output


the value of a global variable
let myName = ‘External Script’
JS

function readName( ) { console.log( myName ) }


readName( )
external.js

l 2 Create an HTML document that includes the external


script and adds a similar script
<script src=”external.js”></script>
<script>
let myName = ‘Internal Script’ scope.html
function getName( ) { console.log( myName ) }
getName( )
</script>

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.

l 1 Create an HTML document with a script that assigns a


self-invoking anonymous function to a global variable
const add = ( function ( ) {
// Statements to be inserted here.
})()
closure.html

l 2 Next, insert statements to initialize a local variable and


assign a function to a local variable in the same scope
let count = 0
const nested = function ( ) { return count = count + 1 }
24

l 3 Now, insert a statement to return the inner function –


assigning the inner function to the global variable
return nested

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

It can be difficult to grasp the concept of closures, as it would


seem that the count variable in this example should be destroyed
when the self-invoking function has completed execution. In
order to better understand how closures work, you can explore the
prototype property of the assigned function.

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>

• JavaScript can display output in an HTML element in an


alert dialog box or in the browser’s console window.

• JavaScript statements may contain keywords, operators, values,


and expressions.

• The JavaScript interpreter ignores tabs and spaces.


• function
JavaScript statements can be grouped in curly bracket
{}
blocks that can be called to execute when required.

• Variable and function names may comprise letters, numbers,


and underscore characters, but must avoid keywords.

• JavaScript variables may contain data types of String, Number,


Boolean, Object, Function, Symbol, , and
null .
undefined

• 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.

• Adatafunction block can include a statement to specify


return
to be passed back to the caller.

• The JavaScript parentheses operator calls the function.


()

• Hoisting allows function calls to appear in the script before


the function declaration.

• Anonymous function expressions have no function name.


• Lexical scope is the environment in which the variable was
created and can be global, local, or closure.

• Local variables should be used to store values, but global


variables can be assigned functions to create closures.

• Aretains
closure is a function nested within an outer function that
access to variables declared in the outer function.

You might also like