Week 5
135
Week 3/4 Review
▪ What are the various techniques to associate an event handler with
an event trigger and why would you use each?
▪ You have a function defined as follows:
calc = (a, b) => a % b;
Call the function such that the returned value is 2
▪ Given the code:
a = new Array(3,4,5); a[3]=0; a.push(17);
What is displayed: console.log(a.join('-'))
136
1
Review cont.
▪ A callback function facilitates asynchronous programming by
implementing a polling strategy. [true][false]
▪ The array .map method uses a function to change an array
[true][false]
▪ A difference between forEach() and map() is …
137
Associative Arrays
▪ The index to an array can be a string!
▪ This creates a key-value pair
flowers = [];
flowers["daisy"] = 12 //daisy is the key, 12 is the value
flowers["rose"] = 15
flowers["carnation"] = 8
document.write(flowers["rose"]) //displays 15
for (key in flowers)
document.write(key + " $" + flowers[key] + " - ")
//Output: daisy $12 - rose $15 - carnation $8
138
2
Try it
▪ Create an associative array of (5) cities and the state they are in
The cities should be the keys.
▪ Display cities only
▪ Create a function called findState() return a state given the city and
the global array
139
JS Objects
▪ An object can be a set of name - value pairs:
var flowers = {
daisy: 12,
rose: 15,
carnation: 8
}
document.write (flowers['rose’]) //displays 15
document.write (Object.keys(flowers))
// displays: daisy,rose,carnation
140
3
Or is it an associative array?
flowers["tulip"] = 7;
document.write (Object.keys(flowers))
141
Try it
▪ Create a JavaScript object using the same city / state data
▪ Display cities only using Object.keys()
▪ Rewrite findState() to first check if a city is a valid key and then return
its state.
142
4
Destructuring an Array
▪ Destructuring assigns parts of an array to other variables
▪ Given:
x = [33,5,44,63];
We could do:
first = x[0];
second=x[1];
third=x[2];
▪ Using destructuring:
var[first, second, third] = x;
143
Try It
Destructuring can be a mechanism to quickly create several variables.
Use destructuring to assign the age of Tom, Bill, Pat, Jen, and Tess the
values: 45, 34,28,and 38 respectively.
144
5
Try It
You can get the current date and time using
new Date()
there are several methods to extract the various parts of the date
see: https://www.w3schools.com/jsref/jsref_obj_date.asp
▪ Create an object with the values of the current numeric month, day, and
year
▪ Assign the object to variables: month, day, year using destructuring
▪ Display the date in the form 1/1/2020
▪ Think about: how would you assign the month and year only?
145
Destructuring and functions
function findLess(arr, target)
{
matches=[];
for (var i=0; i<arr.length; i++)
{
if (arr[i] < target)
matches.push(arr[i]);
}
return matches;
}
//find the largest number in the data set that is less than 35
arr = [33,5,40,44,3,40];
var [lastMatch] = findLess(arr, 35).sort().reverse();
//How could you rework findLess() using forEach?
146
6
But wait! There’s a method for that.
▪ .filter() create a new array based on a filter
▪ arguments a function that provides the criteria for which
items to “keep”
▪ The findLess function could be simplified to:
function findLess(array, target)
{
return array.filter(item => item < target);
}
147
Or …
arr = [33,5,40,44,3,40];
var [lastMatch] =
arr.filter(item => item < 35).sort().reverse();
Test: the result will be 5. Why?
148
7
The result is 5 because sort is looking at the data as strings
The solution is to guide sort as to the correct way to order the data
var [lastMatch] = arr.filter(item => item < 35)
.sort((a, b) => a - b)
.reverse();
149
Try it
▪ Create a function called statistics that returns an array with the
mean, median and mode of an array of numbers.
[mean - average value; median – middle value when data is sorted;
mode – value that appears most frequently]
▪ Use the function to get the median only
150
8
The Spread operator ...
▪ The spread operator returns a subset of an array
▪ Given
x = ['apples', 'pears', 'berries', 'oranges’];
var [pie, ...fruits] = x;
document.write (fruits); // pears,berries,oranges
▪ Or combine two arrays
fruitPies= ['apple','blueberry','peach’];
creamPies=['lemon','chocolate','banana’];
allPies = [...fruitPies,...creamPies];
151
Try it
▪ The spread operator can be used in conjunction with a function parameter
Follow these instructions to create a function that uses the spread operator
to create a function with a variable number of arguments.
– Create a function with two arguments: the first is a value, the second uses the
spread operator
– Initialize sum to the value
– Use forEach with the second argument (which is an array) to iterate through the
values in the array and add them to the start value
– Return the sum
– Test the function
152
9
Try it
▪ You have a list of students in class 1 ( Jane, Alex, Harvey ) and a list
from class 2 (Seymour, Emily, Frank).
▪ Pass them to a function as two strings with each name separated by
a space (ex “Jane Alex”)
▪ In the function split the strings into two arrays (use split)
▪ Combine into one array using the spread operator
▪ Sort the list of names
▪ Display them as a numbered list (use map)
153
Objects in JavaScript
▪ A class is the definition for a set of objects Use “new” to create an instance or object
from a class (sometimes there are
▪ Create a class using the keyword “class” or
via a function shortcuts that do not require new)
▪ Classes in JavaScript have: new implicitly calls the constructor for
– Properties: Characteristics, State the class
– Methods: Things the object can do
– Events: Things the object can respond to
154
154
10
Creating Objects using Functions
▪ The function defines the class and is the constructor method.
▪ Use the keyword “this” to refer to the current instance
function Rectangle(len, wid)
{
this.length = len;
this.width = wid;
}
▪ Instance the class using new:
r = new Rectangle(3,4);
▪ Access the data members using the dot notation
area = r.length * r.width;
155
155
Try it
▪ Create a class in JavaScript called Flower
▪ Flower should have two properties: name and price, that are set in
the constructor
▪ Instance the three flowers we created previously.
▪ Display the name and price of one of the flower objects.
156
156
11
Methods – make the object to do something!
▪ The real utility of objects is when it has Attach the method to the class by assigning it
methods in the constructor
▪ A method is a function that uses the keyword function Rectangle(len, wid)
“this” to refer to members of the object. {
function area() this.length= len;
{ this.width= wid;
return this.length * this.width; this.area= area;
} }
Call the method using the dot notation
r = new Rectangle(3,4);
rectArea = r.area();
157
157
Try it
▪ Modify the Flower class:
▪ Add a method called show() which returns a string with the name and
price (ie: “Rose: $9”)
▪ Display one of the flower objects using the show() method
158
158
12
Example: Array of Objects
▪ Create an array of the three Flower instances
flowers= [daisy,rose,carnation];
Or
flowers = [new Flower('rose', 9), new Flower('carnation', 7), new Flower('daisy', 3)]
▪ Use .map() to create a new collection with the Flower data
collection = flowers.map(f =>f.show());
▪ Display the collection on separate lines:
document.write (collection.join("<br />"))
159
13