Chapter08 JavaScript1LanguageFundamentals
Chapter08 JavaScript1LanguageFundamentals
Language
Fundamentals
Chapter 8
3 4
Variables and Data JavaScript Output
Types
5 Conditionals
6 Loops
7 8
Arrays Objects
9 10
Functions Object
Prototypes
11 Summary
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
HTML is for content and
CSS is for presentation,
JavaScript is for interactivity
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
What is JavaScript
• JavaScript runs right inside the browser
• JavaScript is dynamically typed
• JavaScript is object oriented in that almost everything in the language is
an object
• the objects in JavaScript are prototype-based rather than class-based, which
means that while JavaScript shares some syntactic features of PHP, Java or
C#, it is also quite different from those languages
Although it contains the word Java, JavaScript and Java are vastly different
programming languages with different uses. Java is a full-fledged compiled, object-
oriented language, popular for its ability to run on any platform with a JVM
installed.
Conversely, JavaScript is one of the world’s most popular languages, with fewer of
the object-oriented features of Java, and runs directly inside the browser, without
the need for the JVM.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Client-Side Scripting
Let the client compute
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
What is JavaScript & What Can It Do?
Client-Side Scripting
Figure 8.1 illustrates how a client machine downloads and executes JavaScript code.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Client-Side Scripting
It’s good
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Client-Side Scripting
There are challenges
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Flash and Java Applets
Client-Side Flash
JavaScript is not the only type of client-side scripting.
There are two other client-side approaches to web programming. The most familiar
of these alternatives is Adobe Flash, which is a vector based drawing and animation
program, a video file format, and a software platform that has its own JavaScript-like
programming language called ActionScript.
Flash is often used for animated advertisements and online games, and can also be
used to construct web interfaces.
It is worth understanding how Flash works in the browser.
Flash objects (not videos) are in a format called SWF (Shockwave Flash) and are
included within an HTML document via the <object> tag.
The SWF file is then downloaded by the browser and then the browser delegates
control to a plug-in to execute the Flash file, as shown in Figure 8.2.
A browser plug-in is a software add-on that extends the functionality and
capabilities of the browser by allowing it to view and process different types of web
content. It should be noted that a browser plug-in is different than a browser
extension— these also extend the functionality of a browser but are not used to
process downloaded content.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Client-Side Flash
• Browser Plug-ins
• Flash
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Client-Side Applets
Java Applets
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript History
• JavaScript was introduced by Netscape in their Navigator browser back in 1996. It
originally was called LiveScript, but was renamed partly because one of its original
purposes was to provide a measure of control within the browser over Java
applets.
• JavaScript was only slightly useful, and quite often, very annoying to many users.
At that time, JavaScript had only a few common uses: graphic roll-overs (that is,
swapping one image for another when the user hovered the mouse over an
image), pop-up alert messages, scrolling text in the status bar, opening new
browser windows, and pre-validating user data in online forms.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript in Modern Times
AJAX
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Without JavaScript HTTP request-response loop
how the “normal” HTTP request-
response loop looks. Figure 6.4
illustrates the processing flow for a
page that requires updates based on
user input using the normal
synchronous non-AJAX page request-
response loop. As you can see in
Figure 6.4, such interaction requires
multiple requests to the server, which
not only slows the user experience, it
puts the server under extra load,
especially if, as the case in Figure 6.4,
each request is invoking a server-side
script. With ever-increasing access to
processing power and bandwidth,
sometimes it can be really hard to tell
just how much impact these requests
to the server have, but it’s important
to remember that more trips to the
server do add up, and on a large scale
this can result in performance issues. Figure 6.4 Normal HTTP request-response loop
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
HTTP request-response loop Detail
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
This development has been the creation of JavaScript frameworks, such as
jQuery, Prototype, ASP.NET AJAX, and MooTools.
These JavaScript frameworks reduce the amount of JavaScript code required to
perform typical AJAX tasks. Some of these extend the JavaScript language; others
provide functions and objects to simplify the creation of complex user interfaces.
jQuery, in particular, has an extremely large user base, used on over half of the
top 100,000 websites.
Figure 6.7 illustrates some sample jQuery plug-ins, which are a way for developers
to extend the functionality of jQuery. There are thousands of jQuery plug-ins
available, which handle everything from additional user interface functionality to
data handling.
More recently, sophisticated MVC (Model-View-Controller) JavaScript frameworks
such as AngularJS, Backbone, and Knockout have gained a lot of interest from
developers.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Frameworks Lots of this is done for you, once you get the basics
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Thanks in part to Google, Mozilla, and Microsoft releasing V8, SpiderMonkey, and Chakra (their
respective JavaScript engines) as open-source projects which can be embedded into any C++
application, JavaScript has migrated into other non-browser applications. It can be used as the
language within server-side runtime environment such as Node.js. Some newer non-relational
database systems such as MongoDB use JavaScript as their query language. Complex desktop
applications such as Adobe Creative Suite or OpenOffice.org use JavaScript as their end-user
scripting language.
A wide variety of hardware devices such as the Oculus Rift headset and the Arduino and Raspberry Pi
microcontrollers make use of an embedded JavaScript engine. Indeed, JavaScript appears poised to
be the main language for the emerging Internet of Things.
Part of the reason for JavaScript's emergence as one of, or perhaps even, the most important
programming language in software development, is the vast programming ecosystem that has
developed around JavaScript in the past decade. This ecosystem of JavaScript libraries has made
many previously tricky and tiresome JavaScript tasks much easier.
These libraries of JavaScript functions and objects are generally referred to as JavaScript frameworks.
Some of these frameworks extend the JavaScript language; others provide functions and objects to
simplify the creation of complex user interfaces. jQuery, in particular, has an extremely large user
base, used on over half of the top 100,000 websites. There are thousands of jQuery plug-ins, which
allow a developer to easily add functionality such as image carousels, floating tool tips, modal dialogs,
sortable tables, interactive charts, and many other functions.
The past several years have witnessed a veritable deluge of new JavaScript frameworks. JavaScript
user interface frameworks such as React and jQuery UI have become quite popular among
developers. MVC Frameworks such as AngularJS, Backbone, and Ember have gained a lot of interest
from developers wanting to move more data processing and handling from serverside scripts to HTML
pages using software engineering best practices.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Where does JavaScript go?
JavaScript can be linked to an HTML page in a number of ways.
• Inline
• Embedded
• External
Just as with CSS these can be combined, but external is the preferred
method for cleanliness and ease of maintenance.
Running JavaScript scripts in your browser requires downloading the
JavaScript code to the browser and then running it. Pages with lots of
scripts could potentially run slowly, resulting in a degraded experience
while users wait for the page to load. Different browsers manage the
downloading and loading of scripts in different ways, which are
important things to realize when you decide how to link your scripts.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Inline JavaScript
Mash it in
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Embedded JavaScript
Better
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
External JavaScript
Better
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
External JavaScript
Better
In Listing 6.3, the link to the external JavaScript file is placed within
the <head> element, just as was the case with links to external CSS
files. While this is convention, it is in fact possible to place these links
anywhere within the <body> element. We certainly recommend
placing them either in the <head> element or the very bottom of the
<body> element.
The argument for placing external scripts at the bottom of the
<body> has to do with performance. A JavaScript file has to be loaded
completely before the browser can begin any other downloads
(including images). For sites with multiple external JavaScript files,
this can cause a noticeable delay in initial page rendering. Similarly, if
your page is loading a third-party JavaScript library from an external
site, and that site becomes unavailable or especially slow, then your
pages will be rendered especially slow.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Advanced Inclusion of JavaScript
Imagine for a moment a user with a browser that has JavaScript disabled. When
downloading a page, if the JavaScript scripts are embedded in the page, they must
download those scripts in their entirety, despite being unable to process them. A
subtler version of that scenario is a user with JavaScript enabled, who has a slow
computer, or Internet connection. Making them wait for every script to download may
have a net negative impact on the user experience if the page must download and
interpret all JavaScript before proceeding with rendering the page. It is possible to
include JavaScript in such a way that minimizes these problems. (Due to their
advanced nature the details are described in the labs available for download.)
One approach is to load one or more scripts (or stylesheets) into an <iframe> on
the same domain. In such an advanced scenario, the main JavaScript code in the
page can utilize functions in the <iframe> using the DOM hierarchy to reference
the frame.
Another approach is to load a JavaScript file from within another JavaScript file. In
such a scenario, a simple JavaScript script is downloaded, with the only objective of
downloading a larger script later, upon demand or perhaps after the page has
finished loading.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Users Without Javascript They do exist
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Users Without Javascript They do exist
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
The <noscript> tag
Mechanism to speak to those with JavaScript
Any text between the opening and closing tags will only be displayed to users
without the ability to load JavaScript.
It is often used to prompt users to enable JavaScript, but can also be used to
show additional text to search engines.
Older or mobile browsers may not have a complete JavaScript implementation.
Requiring JavaScript (or Flash) for the basic operation of your site will cause
problems eventually and should be avoided.
This approach of adding functional replacements for those without JavaScript
is also referred to as fail-safe design, which is a phrase with a meaning beyond
web development.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Graceful Degradation and
Progressive Enhancement
Over the years, browser support for different JavaScript objects
has varied. Something that works in the current version of Chrome
might not work in IE version 8; something that works in a desktop
browser might not work in a mobile browser.
There are two strategies:
• graceful degradation
• progressive enhancement
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Graceful Degradation
With this strategy you develop your site for the abilities of current browsers.
For those users who are not using current browsers, you might provide an alternate
site or pages for those using older browsers that lack the JavaScript (or CSS or
HTML5) used on the main site.
The idea here is that the site is “degraded” (i.e., loses capability) “gracefully” (i.e.,
without pop-up JavaScript error codes or without condescending (respect or look
down on) messages telling users to upgrade their browsers)
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Progressive Enhancement
In this case, the developer creates the site using CSS, JavaScript, and HTML
features that are supported by all browsers of a certain age or newer.
To that baseline site, the developers can now “progressively” (i.e., for each
browser) “enhance” (i.e., add functionality) to their site based on the
capabilities of the users’ browsers.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Syntax
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript’s Reputation
Precedes it?
JavaScript’s reputation for being quirky (originally / strange) not only stems
from its strange way of implementing object-oriented principles but also from
some odd syntactic gotchas:
• Everything is type sensitive, including function, class, and variable names.
• The scope of variables in blocks is not supported. This means variables
declared inside a loop may be accessible outside of the loop, counter to
what one would expect.
• There is a === operator, which tests not only for equality but type
equivalence.
• Null and undefined are two distinctly different states for a variable.
• Semicolons are not required, but are permitted (and encouraged).
• There is no integer type, only number, which means floating-point
rounding errors are prevalent even with values intended to be integers.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Variables and Data Types
Example variable declarations and Assignments
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Variables and Data Types
Variables in JavaScript are dynamically typed meaning a variable can be an
integer, and then later a string, then later an object, if so desired.
This simplifies variable declarations, since we do not require the familiar
data-type identifiers (like int, char, and String) of programming languages
like Java or C#. Instead we simply use the var keyword.
Variables should always be defined using the var keyword. While you can in
fact define variables without using var, doing so will give a variable global
scope.
Assignment can happen at declaration-time by appending the value to the
declaration, or at run time with a simple right-to-left assignment
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript is a case-sensitive language. Thus these two lines declare and
initialize two different variables:
var count = 5;
var Count = 9
whitespace around variables, keywords, and other symbols have no meaning.
Indeed, as can be seen in Figure 8.7 , a single line of JavaScript can span multiple
lines.
There are two styles of comment in JavaScript, the end-of-line comment which starts
with two slashes //, and the block comment, which begins with /* and ends with */.
JavaScript accepts a very wide range of symbols within identifier (that is, variable or
function) names. An identifier must begin with a $, _, or any character within one of
several different Unicode categories (we need not list them all here). This means a
JavaScript variable or function name can look quite unusual in comparison to a
language like Java.
For instance, the following are all valid JavaScript variables.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Variables and Data Types
Data Types
JavaScript has t two basic data types:
• reference types (usually referred to as objects) and
• primitive types
Primitive types represent simple forms of data, like Boolean, Number, String,
…
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Reference Types
Variables and Data Types
Primitive variables contain the value of the primitive directly within memory. In contrast,
object variables contain a reference or pointer to the block of memory associated with the
content of the object. Figure 8.8 illustrates the difference in memory between primitive and
reference variables
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Even though the variables def and xyz in Figure 8.8 have the same content,
because they are primitive types, they have separate memory locations. Thus, if
we change the content of variable def, it will have no effect on variable xyz. But as you can
see, since the variables foo and bar are reference types, they point to the memory of an
object instance. Thus changing the object they both point to (e.g., bar[0]=200) affects
both instances (e.g., both bar[0] and foo[0] are equal to 200).
Reference Types
Reference types are more generally referred to as objects. JavaScript has a variety of
objects you can use at any time, such as arrays, functions, and the built-in objects. Some
of the most commonly used built-in objects include: Object, Function, Boolean, Error,
Number, Math, Date, String, and Regexp.
We will also frequently make use of several vital objects which are not part of the
language, but are part of the browser environment. These include the document, console,
and window objects.
All of these objects have properties and methods that you can use. For instance, the
following example creates an object that uses one of these built-in functions (via the new
keyword) and then invokes the toString() method.
var def = new Date();
// sets the value of abc to a string containing the current date
var abc = def.toString();
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
In object-oriented languages, a property is a piece of data that “belongs” to an
object; a method is an action that an object can perform.
To access the properties or methods of an object, you generally will use dot notation. For
instance, the following two lines access a property and a method of the built-in Math object.
var pi = Math.PI;
var tmp = Math.random();
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Output
When first learning JavaScript, one often uses the alert() method. It makes the
browser show a pop-up to the user, with whatever is passed being the message
displayed. The following JavaScript code displays a simple hello world message
in a pop-up:
alert("Hello world");
The pop-up may appear different to each user depending on their browser
configuration. What is universal is that the pop-up obscures the underlying web
page, and no actions can be done until the pop-up is dismissed.
Alerts are generally not used in production code, but are a useful tool for
debugging and illustration purposes. Using alerts can get tedious fast. You have
to click OK, and if you use it in a loop you may spend more time clicking OK than
doing meaningful work.
When using debugger tools in your browser you can write output to a log with:
console.log("Put Messages Here");
And then use the debugger to access those logs.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Output
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Output
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Output
Chrome JavaScript Console
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
JavaScript Output
Fun with document.write()
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Conditionals If, else if, else
JavaScript's syntax for conditional statements is almost identical to that of
PHP, Java, or C++. In this syntax the condition to test is contained within ()
brackets with the body contained in {} blocks. Optional else if statements
can follow, with an else ending the branch.
if…else construct much more frequently than the switch statement since it gives
you more control over conditional tests and more easily allows for nested
conditional logic.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Conditionals switch
The switch statement is similar to a series of if…else statements.
if…else construct much more frequently than the switch statement since it
gives you more control over conditional tests and more easily allows for
nested conditional logic.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Comparator Operations
True or not True
Operator Description Matches (x=9)
(x==9) is true
== Equals
(x=="9") is true
(x==="9") is false
=== Exactly equals, including type
(x===9) is true
Just like with Java, C#, and PHP, JavaScript expressions use the double equals (==)
for comparison. If you use the single equals in an expression, then variable
assignment will occur.
What is unique in JavaScript is the triple equals (===), which only returns true if both
the type and value are equal. This comparator is needed because JavaScript will
coerce a primitive type to an object type when it is being compared to another object
with the double equals. JavaScript will also use type coercion when comparing two
primitive values of different types.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Conditionals Truthy and Falsy
In JavaScript, a value is said to be truthy if it translates to true,
while a value is said to be falsy if it translates to false.
All values in JavaScript, with a few exceptions described hortly,
are truthy.
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Loops
While and do . . . while Loops
Loops are used to execute a code block repeatedly. JavaScript defines three principal statements
for executing loops: the while statement, the do…while statement, and the for statement.
Like conditionals, loops use the () and {} blocks to define the condition and the body of the loop
respectively.
As you can see from this example, while loops
normally initialize a loop control variable before the
loop, use it in the condition, and modify it within the
loop. One must be sure that the variables that make
up the condition are updated inside the loop (or
elsewhere) to avoid an infinite loop!
For Loops
A for loop combines the common components of a loop: initialization, condition, and post-
loop operation into one statement.
This statement begins with the for keyword and has the components placed between ( )
brackets, semicolon (;) separated as shown
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Arrays
Arrays are one of the most commonly used data structures in programming.
In general, an array is a data structure that allows the programmer to collect
a number of related elements together in a single variable.
JavaScript provides two main ways to define an array.
• object literal notation: is the most common way, which has the
following syntax:
var name = [value1, value2, … ];
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Arrays
object literal notation
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Arrays Some common features
• arrays in JavaScript are zero indexed, and the last element at the value of the
array's length property minus 1
• [] notation for access
• .length: gives the length of the array
• .push(): to add an item to the end of an existing array
• .pop(): can be used to remove the last element from an array
• .Join(): joins all array elements into a string.
• .concat(): method creates a new array by merging (concatenating) existing arrays.
• .Slice(): method slices out a piece of an array into a new array.
• .reverse(): method reverses the elements in an array.
• .shift(): method removes the first array element and "shifts" all other elements to
a lower index. Shifting is equivalent to popping, but working on the first element
instead of the last.
• .sort(): method sorts an array alphabetically.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Arrays
Arrays Illustrated
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8
1 2
JavaScript 1: Where Does
Language
JavaScript Go?
Fundamentals
3 Variables and
Data Types 4 JavaScript
Output
5 Conditionals
6 Loops
7 8
Arrays Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
In JavaScript, objects are a collection of named values (which are called properties
in JavaScript). Almost everything within JavaScript is an object (or can be treated
as an object).
Unlike languages such as C++ or Java, objects in JavaScript are not created from
classes. Until ES2015 (ECMAScript 2015, last update) added classes, JavaScript has
lacked classes (however, at the time of writing, this addition to the language is
poorly supported by the major browsers).
JavaScript is a prototype-based language in that new objects are created from
already existing prototype objects.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Objects
Object Creation—Object Literal Notation
JavaScript has several ways to instantiate new objects. The most common way is to use object
literal notation (which we also saw earlier with arrays). In this notation, an object is represented
by a list of key-value pairs with colons between the key and value, with commas separating key-
value pairs, as shown in the following example:
var objName = {
name1: value1,
name2: value2,
// ...
nameN: valueN
};
To reference this object's properties, we can use either dot-notation or square bracket notation.
For instance, in the object just created, we can access the first property using either of the
following.
• objName.name1
• objName["name1"]
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Objects
Object Creation—Object Literal Notation
Which of these should you use? Generally speaking, you will want to use dot
notation since it is easier to type and read. However, if you need to
dynamically access a property of an object whose name is unknown at design
time (i.e., will be determined at run-time), then square bracket notation will be
needed. As well, if a property name has a space or hyphen or other special
character, then square bracket notation will also be needed.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Objects
Object Creation—Constructed Form
Another way to create an instance of an object is to use the constructed form, as
shown in the following:
// first create an empty object
var objName = new Object();
// then define properties for this object
objName.name1 = value1;
objName.name2 = value2;
You may wonder if it is possible to create empty objects with literal notation as well.
The answer is yes, and the technique is as follows:
// create an empty object using literal notation
var obj2 = {};
It should be noted that there really is no such thing as an “empty object” in
JavaScript. All objects inherit a set of properties from the Object.prototype property.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8 cont.
9 10
Functions Object
Prototypes
11 Summary
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions Function Declarations vs. Function Expressions
Functions are the building block for modular code in JavaScript. They are defined by
using the reserved word function and then the function name and (optional)
parameters. Since JavaScript is dynamically typed, functions do not require a return
type, nor do the parameters require type specifications.
Function to calculate a subtotal, which we will define here as the price of a product
multiplied by the quantity purchased. Such a function might be defined as follows
using literal notation.
function subtotal(price, quantity) {
return price * quantity;
}
The above is formally called a function declaration, called or invoked by using the ()
operator
var result = subtotal(10,2);
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Function Declarations vs. Function Expressions
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Anonymous Function Expressions
the function name is more or less irrelevant since we invoked the function
via the object variable name. As a consequence, it is conventional to leave
out the function name in function expressions, as shown in Listing 8.11.
Such functions are called anonymous functions.
};
// invokes the function
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Nested Functions
Nested functions are only visible to the function it is contained within. Thus calculateTax() is only available
within its parent function, that is, calculateTotal().
function calculateTotal(price,quantity) {
function calculateTax(subtotal) {
return tax;
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions Hoisting in JavaScript
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions Callback Functions
One of the most common byproducts of the fact that JavaScript function expressions are full-
fledged objects is that we can pass a function as a parameter to another function. The function
that receives the function parameter is able to call the passed-in function at some future point.
Such a passed-in function is said to be a callback function and are an essential part of real-
world JavaScript programming. A callback function is thus simply a function that is passed to
another function.
Notice how the
calcTax() function is
passed as a variable
(i.e., without
brackets) to the
calculateTotal()
function. In this
example, calcTax() is
a function expression,
but it could have
worked just the same if
it was a function
declaration instead.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Callback Functions
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Objects and Functions Together
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Scope in JavaScript
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Functions
Function Constructors
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8 cont.
9 10
Functions Object
Prototypes
11 Summary
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Object Prototypes
There’s a better way
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Object Prototypes
Methods get duplicated…
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Object Prototypes
Using Prototypes reduces duplication at run time.
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Object Prototypes
Using Prototypes to Extend Other Objects
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Chapter 8 cont.
9 10
Functions Object
Prototypes
11 Summary
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Summary
Key Terms
ActionScript ES2015 libraries
Adobe Flash ES6 loop control variable
anonymous functions exception method
assignment expressions minification
AJAX external JavaScript files module pattern
applet falsy namespace conflict
arrays fail-safe design problem
arrow functions for loops objects
associative arrays functions object literal notation
browser extension function constructor primitive types
browser plug-in function declaration property
built-in objects function expression prototypes
callback function inline JavaScript reference types
client-side scripting immediately-invoked scope (local and global)
closure function strict mode
conditional assignment Java applet throw
dot notation JavaScript frameworks truthy
dynamically typed JavaScript Object Notation try. . . catch block
ECMAScript JSON undefined
embedded JavaScript lexical scope variables
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.
Summary
Questions?
Randy Connolly and Ricardo Hoar Modified by Mohammed Siddiqui Fundamentals of Web Development - 2nd Ed.