Fundamentals of Web Development Chapter 10 PDF
Document Details
Uploaded by Deleted User
Randy Connolly and Ricardo Hoar
Tags
Summary
This chapter details JavaScript array functions like forEach, find, filter, map, reduce, and sort, using examples. It also covers asynchronous programming, fetching data, browser APIs, and web storage.
Full Transcript
Fundamentals of Web Development Third Edition by Randy Connolly and Ricardo Hoar Chapter 10 JavaScript 3: Additional Features...
Fundamentals of Web Development Third Edition by Randy Connolly and Ricardo Hoar Chapter 10 JavaScript 3: Additional Features Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved In this chapter you will learn... Additional language features in JavaScript How to asynchronously consume web APIs in JavaScript Extend the capabilities of your pages using browser APIs Utilize external APIs for mapping and charting Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Array Functions forEach() iterate through an array find() find the first object whose property matches some condition filter() find all matches whose property matches some condition map() is similar manner to filter except it creates a new array of the same size whose values have been transformed by the passed function reduce() reduces an array into a single value sort() sorts a one-dimensional array Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Array forEach() Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Array find() One of the more common coding scenarios with an array of objects is to find the first object whose property matches some condition. This can be achieved via the find() method of the array object, as shown below. const courbet = paintings.find( p => p.artist === 'Courbet' ); console.log(courbet.title); // Burial at Ornans Like the forEach() method, the find() method is passed a function; this function must return either true (if condition matches) or false (if condition does not match). In the example code above, it returns the results of the conditional check on the artist name. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Array filter() If you were interested in finding all matches you can use the filter() method, as shown in the following: // vangoghs will be an array containing two painting objects const vangoghs = paintings.filter(p => p.artist === 'Van Gogh’); Since the function passed to the filter simply needs to return a true/false value, you can make use of other functions that return true/false. For instance, you could perform a more sophisticated search using regular expressions. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Array map() The map() function operates in a similar manner except it creates a new array of the same size but whose values have been transformed by the passed function. Listing 10.2 shows map using DOM nodes. Figure 10.2 uses strings. // create array of DOM nodes const options = paintings.map( p => { let item = document.createElement("li"); item.textContent = `${p.title} ($ {p.artist})`; return10.2 LISTING item; Using the map() function }); Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Reduce The reduce() function is used to reduce an array into a single value. Like the other array functions in this section, the reduce() function is passed a function that is invoked for each element in the array. This callback function takes up to four parameters, two of which are required: the previous accumulated value and the current element in the array. For instance, the following example illustrates how this function can be used to sum the value property of each painting object in our sample paintings array: let initial = 0; const total = paintings.reduce( (prev, p) => prev + p.value, initial); Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Sort sort() function sorts in ascending order (after converting to strings if necessary) const names = ['Bob', 'Sue', 'Ann', 'Tom', 'Jill']; const sortedNames = names.sort(); // sortedNames contains ["Ann", "Bob", "Jill", "Sue", "Tom"] If you need to sort an array of objects based on one of the object properties, you will need to supply the sort() method with a compare function that returns either 0, 1, or −1, depending on whether two values are equal (0), the first value is greater than the second (1), or the first value is less than the second (−1). Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Custom sort const sortedPaintingsByYear = paintings.sort( function(a,b) { if (a.year < b.year) return -1; else if (a.year > b.year) return 1; else return 0; } ); // more concise version using ternary operator and arrow syntax const sorted2 = paintings.sort( (a,b) => a.year < b.year? -1: 1 ); LISTING 10.3 Sorting an array based on the properties of an object Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Asynchronous Coding with JavaScript asynchronous code is code that is doing (or seemingly doing) multiple things at once. In multi-tasking operating systems, asynchronous execution is often achieved via threads: each thread can do only one task at a time, but the operating system switches between threads Many contemporary web sites make use of asynchronous JavaScript data requests of Web APIs, thereby allowing a page to be dynamically updated without requiring additional HTTP requests. A web API is simply a web resource that returns data instead of HTML, CSS, JavaScript, or images Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Normal HTTP request–response loop Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Asynchronous data requests Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Fetching Data from a Web API To illustrate fetch, consider the scenario of a page containing a element. When the user selects from the country list, the page makes an asynchronous request to retrieve a list of cities for that country. let cities = fetch('/api/cities.php? country=italy'); Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Fetching Data from a Web API (ii) So what does cities contain after this call? You might expect it to contain the requested JSON data. But it doesn’t. Why? Because it will take time for this service to execute and respond to our request. What the above fetch will return instead is a special Promise object. Promises in JavaScript are usually handled by invoking two methods: then() for responding to the successful arrival of data, and catch() for responding to an unsuccessful arrival. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Example of asynchronous request using fetch Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Common Mistakes with Fetch Students often struggle at first with using fetch and often commit some version of the mistake shown in Figure 10.14. Multiple nested fetches can be problematic, Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Cross-Origin Resource Sharing Modern browsers prevent cross-origin requests by default (Chapter 16), so sharing content legitimately between two domains becomes harder. Cross-origin resource sharing (CORS) is a mechanism that uses new HTTP headers in the HTML5 standard that allows a JavaScript application in one origin (i.e., a protocol, domain, and port) to access resources from a different origin. If an API site wants to allow any domain to access its content through JavaScript, it would add the following header to all of its responses: Access-Control-Allow-Origin: * Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Fetching Using Other HTTP Methods By default, fetch uses the HTTP GET method. There are times when you will instead want to use POST, or even PUT or DELETE For instance, imagine you wanted to add an item to a favorites list or to a shopping cart in an asynchronous manner. This would typically require sending data to the server, so a POST fetch makes the most sense. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Adding a Loading Animation Fetching takes time. A common user interface feature is to supply the user with a loading animation while the data is being fetched. Simply show or hide an element that contains either an animated GIF, or, even better, CSS that uses animation Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Promises A Promise is a placeholder for a value that we don’t have now but will arrive later. Eventually, that promise will be completed and we will receive the data, or it won’t, and we will get an error instea, Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Executing multiple Promises in parallel For executing multiple promises, you can make use of the Promise.all() method, which returns a single Promise when a group of Promise objects have been resolved. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Async and Await ES7 introduced the async...await keywords that can both simplify the coding and even eliminate the typical nesting structure of typical asynchronous coding. Recall this sample line from the earlier section on fetch? let obj = fetch(url); Content is contained in the variable obj is a Promise; the then() method of the Promise object needs to be called and passed a callback function that will use the data from the promisified function fetch. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Async and Await (ii) The await keyword provides exactly that functionality, namely, the ability to treat asynchronous functions that return Promise objects as if they were synchronous. let obj = await fetch(url); Now, obj will contain whatever the resolve() function of the fetch() returns, which in this case is the response from the fetch. Notice that no callback function is necessary! There is an important limitation with using the await keyword: it must occur within a function prefaced with the async keyword Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Using Browser APIs In the last section, you learned how to use the fetch() method to access data from external APIs. In this section, you will instead make use of the browser APIs In recent years, the amount of programmatic control available to the JavaScript developer has grown tremendously. You can now, for instance, retrieve location information, access synthesized voices, recognize and transcribe speech, and persist data content in the browser’s own local storage. Table 10.1 lists several of the more important browser APIs. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Web Storage API The Web Storage API provides a mechanism for preserving non-essential state across requests and even across sessions. It comes in two varieties: localStorage is a dictionary of strings that lasts until removed from the browser. sessionStorage is also a dictionary of strings but only lasts as long as the browsing session. To add a string to either involves calling the setItem() method of the localStorage or sessionStorage objects. To retrieve a value from either simply requires using the getItem() method. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Web Storage API (ii) The Web Storage API provides a mechanism for preserving non-essential state across requests and even across sessions. It comes in two varieties: localStorage is a dictionary of strings that lasts until removed from the browser. sessionStorage is also a dictionary of strings but only lasts as long as the browsing session. To add a string to either involves calling the setItem() method of the localStorage or sessionStorage objects. To retrieve a value from either simply requires using the getItem() method. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved GeoLocation The Geolocation API provides a way for JavaScript to obtain the user’s location (accuracy/availability dependent on permission and device) if (navigator.geolocation) { position.coords.latitude; const longitude = navigator.geolocation.getCurrentPositio position.coords.longitude; n(hav eLocation,geoError); const altitude = } else { position.coords.altitude; // geolocation not supported or const accuracy = accepted position.coords.accuracy;... // now do something with this } information... LISTING 10.13 Sample GeoLocation API usage } function haveLocation(position)Copyright © { 2021, 2018, function geoError(error) 2015 Pearson { All Education, Inc....Rights } Reserved Key Terms async... await sharing (CORS) localStorage prototype asynchronous external API map() promise code fetch() module service workers browser API forEach() origin threads card find() offline first TypeScript class filter() Progressive Web web API cross-origin resource Geolocation API Applications Web Storage API (PWA) Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials. Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved