Chapter 8
Chapter 8
Chapter 8
JavaScript 1:
Language Fundamentals
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
In this chapter you will learn . . .
• About JavaScript’s role in contemporary web development
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
What Is JavaScript and What Can It Do?
• JavaScript: it is an object-oriented, dynamically typed scripting language
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Client-Side Scripting
Client-side scripting refers to
the client machine (i.e., the
browser) running code locally
rather than relying on the
server to execute code and
return the result.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Client-Side Scripting: Advantages
• Processing can be off-loaded from the server to client machines, thereby
reducing the load on the server.
• The browser can respond more rapidly to user events than a request to a
remote server ever could, which improves the user experience.
• JavaScript can interact with the downloaded HTML in a way that the server
cannot, creating a user experience more like desktop software than simple
HTML ever could.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Client-Side Scripting: Disadvantages
• There is no guarantee that the client has JavaScript enabled, meaning any
required functionality must be implemented redundantly on the server.
• JavaScript is not fault tolerant. Browsers are able to handle invalid HTML
or CSS. But if your page has invalid JavaScript, it will simply stop
execution at the invalid line.
• The Sixth Edition (or ES6) was the one that introduced many notable new
additions to the language (such as classes, iterators, arrow functions, and
promises)
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JavaScript in Contemporary Software Development
• ….
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Where Does JavaScript Go?
Just as CSS styles can be inline, embedded, or external, JavaScript can be
included in a number of ways.
• Inline JavaScript refers to the practice of including JavaScript code directly
within some HTML element attributes.
• Embedded JavaScript refers to the practice of placing JavaScript code within a
<script> element
• The recommended way to use JavaScript is to place it in an external file. You do this
via the <script> tag
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Adding JavaScript to a page
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Users without JavaScript
Users have a myriad of reasons for not using JavaScript
– Search engines
– Browser extensions
– Text browser
– Accessible browser
HTML provides an easy way to handle users who do not have JavaScript
enabled: the <noscript> element. Any text between the opening and closing
tags will only be displayed to users without the ability to load JavaScript.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Variables and Data Types
Variables in JavaScript are dynamically
typed, meaning that you do not have to
declare the type of a variable before you
use it.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JavaScript Output
alert() Displays content
within a browser-controlled
pop-up/modal window.
prompt() Displays a
message and an input field
within a modal window.
confirm() Displays a
question in a modal window
with ok and cancel buttons.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JavaScript Output (ii)
• document.write()
Outputs the content (as
markup) directly to the
HTML document.
• console.log() Displays
content in the browser’s
JavaScript console.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Document.write() note
NOTE
While several of the examples in this chapter make use of
document.write(), the usual (and more trustworthy) way to
generate content that you want to see in the browser window will
be to use the appropriate JavaScript DOM (Document Model
Object) method. You will learn how to do that in the next chapter.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Data Types
JavaScript has two basic data types:
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Primitive Types
• Boolean True or false value.
• Number Represents some type of number. Its internal format is a double precision
64-bit floating point value.
• Undefined Has only one value: undefined. This value is assigned to variables that
are not initialized. Notice that undefined is different from null.
• Symbol New to ES2015, a symbol represents a unique value that can be used as a
key value.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Primitive vs Reference Types
Primitive variables contain
the value of the primitive
directly within memory.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Let vs const
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Built-In 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.
Later we will also frequently make use of several vital objects that are not part
of the language but are part of the browser environment. These include the
document, console, and window objects.
let def = new Date();
// sets the value of abc to a string containing the current date
let abc = def.toString();
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Concatenation
const country = "France";
const city = "Paris";
To combine string literals const population = 67;
const count = 2;
together with other variables.
Use the concatenate let msg = city + " is the capital of " + country;
msg += " Population of " + country + " is " + population;
operator (+).
let msg2 = population + count;
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Conditionals
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.
JavaScript has all of the expected comparator operators (<, >, ==, <=, >=, !=,
!==, ===) which are described in Table 8.4.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Switch statement
switch (artType) {
case "PT":
The switch statement is output = "Painting";
break;
similar to a series of if...else case "SC":
statements. output = "Sculpture";
break;
default:
There is another way to output = "Other";
make use of conditionals: the }
// equivalent
conditional operator (also if (artType == "PT") {
called the ternary operator). output = "Painting";
} else if (artType == "SC") {
output = "Sculpture";
} else {
output = "Other";
}
LISTING 8.4 Conditional statement using switch and an
equivalent if-else
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
The conditional (ternary) operator
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Truthy and Falsy
Everything in JavaScript has an inherent Boolean value.
All values in JavaScript are truthy except false, null, "", '', 0, NaN, and
undefined
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
While and do . . . while Loops
let count = 0;
while (count < 10) {
While and do…while loops execute
// do something
nested statements repeatedly as long // ...
as the while expression evaluates to count++;
true. }
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
For Loops
For loops combine the common components of a loop—initialization,
condition, and postloop operation—into one statement. This statement begins
with the for keyword and has the components placed within () brackets, and
separated by semicolons (;)
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Infinite Loop Note
NOTE
Infinite loops can happen if you are not careful, and since the
scripts are executing on the client computer, it can appear to them
that the browser is “locked” while endlessly caught in a loop,
processing.
Some browsers will even try to terminate scripts that execute for
too long a time to mitigate this unpleasantness.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Try…catch
DIVE DEEPER
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Arrays
Arrays are one of the most commonly used data structures in programming.
First approach is Array literal notation, which has the following syntax:
• const name = [value1, value2, ... ];
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Array example
const years = [1855, 1648, 1420];
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Iterating an array using for . . . of
ES6 introduced an alternate way to
iterate through an array, known as the
for...of loop, which looks as follows.
// iterating through an array //functionally equivalent to
for (let yr of years) { for (let i = 0; i < years.length; i++) {
console.log(yr); let yr = years[i];
} console.log(yr);
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Array Destructuring
Let’s say you have the following array:
const league = ["Liverpool", "Man City", "Arsenal", "Chelsea"];
Now imagine that we want to extract the first three elements into their own variables.
The “old-fashioned” way to do this would look like the following:
let first = league[0];
let second = league[1];
let third = league[2];
By using array destructuring, we can create the equivalent code in just a single line:
let [first,second,third] = league;
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Objects
We have already encountered a few of the built-in objects in JavaScript,
namely, arrays along with the Math, Date, and document objects.
In this section, we will learn how to create our own objects and examine some
of the unique features of objects within JavaScript.
Unlike languages such as C++ or Java, objects in JavaScript are not created
from classes. JavaScript is a prototype based language, in that new objects
are created from already existing prototype objects, an idea that we will
examine in Chapter 10.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Object Creation Using Object Literal Notation
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Object Creation Using Object Constructor
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Objects containing other content
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Object Destructuring
const photo = {
Just as arrays can be destructured,
id: 1,
so too can objects.
title: "Central Library",
location: {
country: "Canada",
city: "Calgary"
Let’s use the following object literal
}
definition.
};
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Object Destructuring (ii)
One can extract out a given property Equivalent assignments using object
using dot or bracket notation as follows. destructuring syntax would be:
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Spread
You can also make use of the spread syntax to copy contents from one array
into another. Using the photo object from the previous section, we could copy
some of its properties into another object using spread syntax:
const foo = { name:"Bob", .. .photo.location, iso:"CA" };
Is equivalent to:
const foo = { name:"Bob", country:"Canada", city:"Calgary", iso:"CA"};
It should be noted that this is a shallow copy, in that primitive values are
copied,but for object references, only the references are copied.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JSON
JavaScript Object Notation or JSON is used as a language-independent data
interchange format analogous in use to XML.
The main difference between JSON and object literal notation is that property names
are enclosed in quotes, as shown in the following example:
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JSON object
The string literal on the last slide contains an object definition in JSON format (but is
still just a string). To turn this string into an actual JavaScript object requires using
the built-in JSON object.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
JSON in contemporary web development
JSON is encountered frequently in
contemporary web development.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Functions
Functions are defined by using the reserved word function and then the
function name and (optional) parameters.
Functions do not require a return type, nor do the parameters require type
specifications.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Declaring and calling functions
A function to calculate a subtotal as the price of a product multiplied by the
quantity might be defined as follows:
function subtotal(price,quantity) {
return price * quantity;
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Function expressions
// defines a function using an anonymous function expression
The object nature of functions const calculateSubtotal = function (price,quantity) {
can be further seen in the next return price * quantity;
};
example, which creates a
function using a function // invokes the function
expression. let result = calculateSubtotal(10,2);
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Default Parameters
In the following code, what will happen (i.e., what will bar be equal to)?
function foo(a,b) {
return a+b;
}
let bar = foo(3);
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Rest Parameters
function concatenate(...args) {
How to write a function that can let s = "";
take a variable number of for (let a of args)
parameters? s += a + " ";
return s;
The solution is to use the rest }
operator (...) let girls =
concatenate("fatima","hema","jane","alilah");
The concatenate method takes
let boys = concatenate("jamal","nasir");
an indeterminate number of
string parameters separated by
console.log(girls); // "fatima hema jane alilah“
spaces.
console.log(boys); // "jamal nasir“
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Nested Functions
function calculateTotal(price,quantity) {
The object nature of functions let subtotal = price * quantity;
can be further seen in the next return subtotal + calculateTax(subtotal);
example, which creates a
function using a function
expression. // this function is nested
function calculateTax(subtotal) {
When we invoked the function via let taxRate = 0.05;
the object variable name it is return subtotal * taxRate;
conventional to leave out the }
function name for so called
}
anonymous functions
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Hoisting in JavaScript
JavaScript function
declarations are hoisted to
the beginning of their
current level
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Callback Functions
Since JavaScript functions are
full-fledged objects, you can
pass a function as an
argument to another function.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Callback Functions (ii)
We can actually define a function definition directly within the invocation
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Objects and Functions Together
const order ={
In a class-oriented salesDate : "May 5, 2016",
product : {
programming language like price: 500.00,
Java, we say classes define brand: "Acer",
behavior via methods. output: function () { return this.brand + ' $' + this.price; }
},
In a functional programming customer : {
name: "Sue Smith",
language like JavaScript, we address: "123 Somewhere St",
say objects have properties output: function () {return this.name + ', ' + this.address; }
that are functions. }
};
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Function constructors
// function constructor
Looks similar to the function Customer(name,address,city) {
this.name = name;
approach used to create this.address = address;
instances of objects in a this.city = city;
class-based language like this.output = function () {
return this.name + " " + this.address + " " + this.city;
Java };
}
The key difference between
using a function constructor // create instances of object using function constructor
and using a regular function const cust1 = new Customer("Sue", "123 Somewhere", "Calgary");
alert(cust1.output());
resides in the use of the const cust2 = new Customer("Fred", "32 Nowhere St", "Seattle");
new keyword before the alert(cust2.output());
function name. LISTING 8.14 Defining and using a function constructor
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
What happens with a constructor call of a function
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Arrow Syntax
Arrow syntax provide a more concise syntax for the definition of anonymous
functions. They also provide a solution to a potential scope problem
encountered with the this keyword in callback functions.
As you can see, this is a pretty concise (but perhaps confusing) way of writing
code.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Array syntax overview
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Changes to “this” in Arrow Functions
Arrow functions do not have their own this value (see Figure 8.22). Instead,
the value of this within an arrow function is that of the enclosing lexical context
(i.e., its enclosing parental scope at design time).
While this can occasionally be a limitation, it does allow the use of the this
keyword in a way more familiar to object-oriented programming techniques in
languages such as Java and C#.
When we finally get to React development in Chapter 11, the use of arrow
functions within ES6 classes will indeed make our code look a lot more like
class code in a language like Java.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Scope in JavaScript
Scope generally refers to the context
in which code is being executed.
• block scope,
• global scope.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Block scope
Block-level scope means variables
defined within an if {} block or a for
{} loop block using the let or const
keywords are only available within
the block in which they are defined.
But if declared with var within a
block, then it will be available
outside the block.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Global Scope
If an identifier has global scope, it is available everywhere.
In Chapter 10, you will learn of the new module feature in ES6 that helps
address this problem.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Function/Local Scope
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Closures in JavaScript
Scope in JavaScript is sometimes
referred to as lexical scope
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved