Get Started in JavaScript
Get Started in JavaScript
This chapter is an introduction to the exciting world of JavaScript. It demonstrates how to add scripts
to HTML documents that provide JavaScript variables and functions.
Meet JS
Include Scripts
Console Output
Make Statements
Avoid Keywords
Store Values
Create Functions
Assign Functions
Recognize Scope
Use Closures
Summary
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 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 the language “JavaScript”.
Brendan Eich, creator of the JavaScript language, also co-founded the Mozilla project and
helped launch the Firefox web browser.
The JavaScript examples in this book describe three key ingredients:
•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>
[Link]( ‘message’ ).innerText = ‘Hello World!’
</script>
An HTML document can include multiple scripts, and these may be placed in the head or body
section of the document. It is, however, recommended that you place scripts at the end of the
body section (immediately before the </body> closing tag) so the browser can render the web
page before interpreting the script.
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=”[Link]
</script>
You can also specify content that will only appear in the web page if the user has disabled
JavaScript in their web browser by including a <noscript> element in the body of the HTML
document, like this:
You may see a type=”text/javascript” attribute in a <script> tag but this is no longer
required as JavaScript is now the default scripting language for HTML.
Do not include <script> and </script> tags in an external JavaScript file, only the script
code.
External script files can make code maintenance easier but almost all examples in this book
are standalone for clarity, so include the script code between tags directly in the HTML
document.
Console Output
JavaScript can display output by dynamically writing content into an HTML element. For
example, with this code:
The element is identified by the value assigned to its id attribute and the innerText property
specifies text to be written there.
Additionally, JavaScript can display output by writing content into a pop-up dialog box, like this:
When developing in JavaScript, and learning the language, it is initially better to display output
in the browser’s JavaScript console, like this:
[Link]( ‘Hello World!’ )
This calls the log( ) method of the console object to display the content specified within the ( )
parentheses in a console window. All leading browsers have a JavaScript console within their
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.
Notice the use of the . period (full stop) operator to describe properties or methods of an
object using “dot notation”.
The console provides helpful messages if an error occurs in your code – so is great for
debugging the code.
Create an HTML document that includes an empty paragraph and a script to display output
in three ways
<p id=”message”></p>
<script>
[Link]( ‘message’ ).innerText =
‘Hello World!’
[Link]( ‘Hello World!’ )
[Link]( ‘Hello World!’ )
</script>
[Link]
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
Next, hit the F12 key, or use your browser’s menu to open its Developers Tools feature
Now, select the Console tab to see the output written into the console window
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
There is also a [Link]( ) method that replaces the entire header and body of the
web page, but its use is generally considered bad practice.
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.
{
statement
statement
statement
}
The JavaScript keywords are described here and you will learn about operators, values,
and expressions later.
An “expression” produces a value, whereas a “statement” performs an action.
Use the space bar to indent statements, as tab spacing may be treated differently when
viewing the code in text editors.
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 100, or floating-point numbers such as
3.142.
•String literals – text within either double quotes, such as “JavaScript Fun”, or single quotes
such as ‘JavaScript Fun’.
Variable values are called, quite simply, “variables” and are used to store data within a script.
They can be created using the JavaScript 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:
( 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.
Decide on one form of quotes to use in your code for string literals and stick with it for
consistency. The examples in this book use single quotes.
It is often useful to “comment-out” lines of code to prevent their execution when debugging
code.
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
window
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 introduced but is best avoided now as it does not prevent
you declaring the same variable twice in the same context.
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’
A variable name is an alias for the value it contains – using the name in script references its
stored value.
Choose meaningful names for your variables to make the script easier to understand later.
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.
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
let jsObject = console
let jsMethod = [Link]
let jsSymbol = Symbol( )
let emptyVariable = null
let unusedVariable
[Link]
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.
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 [Link](
), 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 [Link]( ) 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:
return result
}
It is common for statements within a function block to include calls to other functions – to
modularize scripts into blocks.
Notice that the preferred format of a function declaration places the { opening curly bracket
on the same line as the function keyword.
You can omit the return statement, or use the return keyword without specifying a value,
and the function will simply return an undefined value to the caller.
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
}
[Link]
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 )
}
Finally, add statements that call the functions and print the returned values in output strings
[Link]( ‘8 x 8: ‘ + square( 8 ) )
[Link]( ‘8 + 20: ‘ + add( 8, 20 ) )
[Link]( ‘8 + 10: ‘ + add( 8 ) )
[Link]( ‘(8 x 8) + (8 + 10): ‘ + squareAdd( 8 ) )
Notice that the default second parameter value (10) is used here when only one argument
value is passed by the caller.
Save the HTML document, then open it in your browser and launch the console to see
values returned from functions
It is important to recognize that the JavaScript ( ) parentheses operator is the component of the
call statement that actually calls the function. This means a statement can assign a function to a
variable by specifying just the function name. The variable can 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.
Variables that were declared using the older var keyword were also hoisted, but those
declared with let or const are not hoisted.
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
process known as “hoisting”. The second sweep is when the script is actually executed by the
interpreter. Hoisting allows function calls to appear in the script before the function declaration,
as the interpreter has already recognized the function on the first sweep. The first sweep does
not, however, recognize functions that have 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:
Create an HTML document with a script that calls a function that has not yet been declared
[Link]( ‘Hoisted: ‘ + add( 100, 200 ) )
[Link]
Now, add a function that assigns the function above to a variable, then calls the assigned
function
let addition = add
[Link]( ‘Assigned: ‘ + addition( 32, 64 ) )
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
}
[Link]( ‘Anonymous: ‘ + anon( 9, 1 ) )
Finally, assign the value returned from a self-invoking function to a variable and display
that value
let iffy = ( function ( ) {
let str = ‘Self Invoked Output’ ; return str
})()
[Link]( iffy )
Save the HTML document, then open it in your browser and launch the console to see
values returned from functions
When assigning a named function to a variable, only specify the function name in the
statement.
The significance of self-invoking functions may not be immediately obvious, but their
importance should become clearer by the 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
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 values without warning. The more recent let and const keywords
prohibit this and instead recognize the behavior as an “Uncaught SyntaxError”. It is therefore
recommended that you create variables declared using the let or const keywords to store values
within your scripts.
You will discover how to catch and handle errors here.
Create an external script that calls a function to output the value of a global variable
let myName = ‘External Script’
function readName( ) { [Link]( myName ) }
readName( )
[Link]
Create an HTML document that includes the external script and adds a similar script
<script src=”[Link]”></script>
<script>
let myName = ‘Internal Script’
function getName( ) { [Link]( myName ) }
getName( )
</script>
[Link]
Save both files in the same folder, then open the HTML document to see a conflict error
reported in the console
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’ ; [Link]( myName )
}
function getName( ) {
let myName = ‘Internal Script’ ; [Link]( myName )
}
The function calls readName( ) and getName( ) remain in the scripts without editing.
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.
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.
})()
[Link]
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 }
Now, insert a statement to return the inner function – assigning the inner function to the
global variable
return nested
Finally, add three identical function calls to the inner function that is now assigned to the
global variable
[Link]( ‘Count is ‘ + add( ) )
[Link]( ‘Count is ‘ + add( ) )
[Link]( ‘Count is ‘ + add( ) )
Save the HTML document, then open it in your browser and launch the console to see
values returned from a closure
Self-invoking function expressions are described here. They execute their statements one
time only. Here, you can use [Link]( add ) to confirm that the function expression has
been assigned to the outer variable.
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.
Add a statement at the end of the script to reveal how the assigned function has been
constructed internally
[Link]( [Link] )
Save the HTML document, then refresh the browser and expand the “constructor”
dropdown to see the scopes
Closer inspection reveals that the assigned function has a special (Closure) scope in addition to
the regular local (Script) scope and outer (Global) scope. This is how the count variable remains
accessible via the assigned function yet, importantly, cannot be referenced in any other way.
The use of closures to hide persistent variables from other parts of your script is an important
concept. It is similar to how “private” variables can be hidden in other programming languages
and are only accessible via “getter” methods.
All JavaScript objects inherit properties and methods from a prototype. Standard
JavaScript objects, such as functions, call an internal constructor function to create the
object by defining its components.
Don’t worry if you can’t immediately understand how closures work. They can seem
mystical at first, but will become clearer with experience. You can continue on and come
back to this technique later.
Summary
•JavaScript code can be included in an HTML document directly or from an external file
using <script> </script> tags.
•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.
•JavaScript statements can be grouped in { } curly bracket function 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, null, and undefined.
•Variables declared with the let keyword can be reassigned new values, but the const
keyword does not allow this.
•A function expression has statements grouped in { } curly brackets for execution, and it
returns a final single value.
•The ( ) parentheses of a function expression may contain parameters for argument values to
be passed from the caller.
•A function block can include a return statement to specify data 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.
•A closure is a function nested within an outer function that retains access to variables
declared in the outer function.