The JavaScript Workshop

4.4 (5 reviews total)
By Joseph Labrecque , Jahred Love , Daniel Rosenbaum and 5 more
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. 1. Getting to Know JavaScript

About this book

You already know you want to learn JavaScript, and a smarter way to learn JavaScript is to learn by doing. The JavaScript Workshop focuses on building up your practical skills so that you can develop cutting-edge applications for web, mobile and desktop users. Alongside knowledge of HTML and CSS, JavaScript is a key skill for those looking to enter professional web development. You'll learn from real examples that lead to real results.

Throughout The JavaScript Workshop, you'll take an engaging step-by-step approach to understanding JavaScript code. You won't have to sit through any unnecessary theory. If you're short on time you can jump into a single exercise each day or spend an entire weekend learning about functional programming and unit testing. It's your choice. Learning on your terms, you'll build up and reinforce key skills in a way that feels rewarding.

Every physical print copy of The JavaScript Workshop unlocks access to the interactive edition. With videos detailing all exercises and activities, you'll always have a guided solution. You can also benchmark yourself against assessments, track progress, and receive content updates. You'll even earn a secure credential that you can share and verify online upon completion. It's a premium learning experience that's included with your printed copy. To redeem, follow the instructions located at the start of your JavaScript book.

Fast-paced and direct, The JavaScript Workshop is the ideal companion for JavaScript beginners. You'll build and iterate on your JavaScript coding skills like a real software developer, learning along the way. This process means that you'll find that your new skills stick, embedded as best practice. A solid foundation for the years ahead.

Publication date:
November 2019
Publisher
Packt
Pages
802
ISBN
9781838641917

 

1. Getting to Know JavaScript

Overview

By the end of this chapter, you will be able to locate JavaScript elements along with other code elements in a web browser; identify different versions of JavaScript supported by various web browsers; construct simple JavaScript commands; discuss the range of modern approaches to JavaScript; describe JavaScript's capabilities and create an alert box popup in a web browser.

This chapter describes the foundational background of JavaScript so that we can move forward and achieve competency with this widely used programming language.

 

Introduction

JavaScript is a language with interesting beginnings. In its early days, it was not taken very seriously—the only widely accepted, functionally correct use for the language was to perform client-side validation of form data. Many developers only copied and pasted simple code snippets that performed a single action on a website they were building. All these code snippets did were very simple actions such as reveal an alert to the user or provide a date countdown—simple logic.

Today, JavaScript is a whole different beast—and one with the power to literally build out entire HTML documents, revise CSS styling on the fly, and securely transport and interpret data from various remote sources. Whereas in times past, HTML was the primary technology on the web, in the present era, JavaScript is king.

Any introduction to JavaScript requires a foundational background of the history and origins of the language in order to move forward and achieve competency. This chapter introduces us to JavaScript, from its history to modern implementations. It also provides us with additional information on various uses of the language so that we can provide a proper context for what comes next.

 

What Is JavaScript and How Is It Used?

JavaScript is a weakly-typed, multi-paradigm, event-driven, object-oriented programming language. It includes the ability to work with strings, dates, arrays, objects, and more. It is generally used on the client-side within web browser environments but can also be used in other environments such as servers and desktop applications. The runtime environment is very important for JavaScript—especially since it, by itself, does not include any networking, file, graphics, or storage capabilities on its own.

JavaScript versus Other Languages

If you are approaching JavaScript with experience in other languages such as Java or Python, things might seem a bit odd. While many languages (such as Java) must be compiled to run, JavaScript is run exactly as-is and does not require this additional step.

Though the language is used within many environments and for many purposes, JavaScript is fundamentally one of the three languages that are native to the web. The other two languages are the HTML semantic markup language and the CSS styling and layout language. All three are very different from one another in purpose and function, but they are all meant to work together in a single environment. Let's go over them:

  • Hypertext Markup Language (HTML): This is the most fundamental of these three languages as it defines the elements that compose an HTML page and defines the flow of basic information that's presented to the user.
  • Cascading Style Sheets (CSS): This is used to define a set of stylistic layout rules, which adds visual flourish and advanced layout to defined HTML elements.
  • JavaScript(JS): This works to enable interactivity in web pages and is what will be the focus of this book.

With all three of these languages, there is a basic understanding of the separation of concerns, that is, HTML provides the content and structure, CSS provides the styling and layout, and JavaScript provides the interactivity. While this understanding still holds sway, many frameworks do not exactly abide by this separation and mix these various languages together in some shape or form. Some developers are okay with this, while others are not. It's definitely an issue to be aware of when getting into this field, but it is ultimately up to you which stance you take, based on your particular needs. In my opinion, there is no hard and fast answer to a question like this.

Exercise 1.01: Languages Discovery

Let's go ahead and examine a website to see whether we can spot how HTML, JavaScript, and CSS are all represented. You can choose any website you like for this exercise.

Note

All the examples and screenshots in this book will use Google Chrome as the web browser of choice. You can use the browser you prefer, though some of the steps that are shown may differ between various browsers.

Let's get started:

  1. Within your web browser, enter a URL in the address bar and press Enter/Return to load the chosen resource. For this example, let's use https://packt.live/2oXOE67—the Angular website. Of course, you can choose any website that you'd like to explore.
  2. Now, right-click anywhere within the browser viewport to summon a contextual menu. Select the option that allows you to view the source code of the page. In Chrome, this is labeled View Page Source.
  3. The source code for the page will then appear in a new tab. You can examine how the page is structured and pick out the various HTML, CSS, and JavaScript elements from the bare source code:
    Figure 1.1: Much can be learned from examining the bare source code

    Figure 1.1: Much can be learned from examining the bare source code

  4. With the source code exposed, scroll down and identify the various HTML elements within the page structure. You'll likely find a <head> tag and a <body> tag (which are mandatory), along with various <p> and <h1> to <h6> tags within the page.

    Here is an example of some basic HTML content (not actually from the Angular website):

    <body>
    <h1>Welcome!</h1>
    <p>Angular is a framework used to build web applications.</p>
    <p>Create high-performing and accessible applications using Angular.</p>
    </body>
  5. Now, try and locate either embedded CSS rules within a <style> element, or even a linked CSS file. Here is an example of some embedded CSS:
    <style>
    color: red; 
    margin-top: 40px; 
    position: relative; 
    text-align center;
    </style>

    And here is a linked CSS file:

    <link rel="stylesheet"href="styles.css">
  6. Finally, we'll locate some JavaScript. Much like CSS, JavaScript can be found embedded within a page using the <script> tag, or entire JavaScript files can be linked though a similar mechanism. Here, we are locating some embedded JavaScript:
    <script>
    function writeMessage() {
    document.getElementById("message").innerHTML = "Hello From JavaScript!";
    }
    </script>

    Here is a linked JavaScript file:

    <script src="main.js"></script>

    Choosing to view the source code of public web pages like this was once a common way to learn about web technologies.

    Note

    In various websites and examples, you may see a type attribute included with the <script> tag specifying type="text/javascript". In HTML5, this is not necessary and is the default attribute. If you must target previous versions of HTML, you will need to specify it.

So far, we have introduced the JavaScript programming language and examined its primary runtime environment (the web browser). We also had a brief look at JavaScript's relationship to HTML and CSS as one of the three native web technologies.

In the next section, we'll take a look at the history of JavaScript and how it has evolved over the years.

 

A Brief History of the JavaScript Language

We've seen how JavaScript is often integrated within a web environment, but how did this language come about? We need to go back to the early 1990s and understand what the web looked like in those days before we begin talking about JavaScript itself.

The story really begins with Netscape and the web browser they created named Netscape Navigator. This new browser was based on the successful Mosaic web browser with the intent to commercialize it. During that time, and depending on who you speak to, Netscape Navigator was the web browser of choice to develop for. Around the middle of the decade, Microsoft released its Internet Explorer browser, which ignited the first browser wars.

Netscape Mocha and LiveScript

Around this same time, Netscape hired Brendan Eich to develop a programming language for Netscape's web browser. Eich took inspiration from Scheme (Lisp), Self, and most importantly, Java. The work on this language, then called Mocha, was initially (and infamously) completed in the time span of only 10 days. With the initial version completed, Netscape changed their name and began calling it LiveScript.

It turned out that LiveScript, as a language name, was just as temporary as Mocha until Netscape partnered with a certain other large company to advance the idea of a two-pronged approach to web development.

Sun Microsystems and Java

The popular Java language came into play with a partnership between Netscape and Sun Microsystems. Sun was looking at the web as the next step for Java, and Netscape was looking for allies in the coming war against Microsoft, so an allegiance was formed. The language being developed by Eich was from then on named JavaScript as it was meant to work alongside Java in the web browser as a more approachable way to add interactivity to that environment.

This would mean that the Java language would be what serious developers used to write interactive content for the web, while JavaScript would provide similar interactive capabilities but was geared more toward hobbyists and those who wanted to tinker.

Note

What happened, of course, was quite different. JavaScript was integrated into the browser well before Java was, and, once Java came on board, it was only through the use of applets. With Java applets falling out of popularity quite some time ago, we are left with JavaScript alone today and not the two languages that were initially envisioned, though the JavaScript name has stuck.

Ecma International and ECMAScript

Ecma adopted and standardized the specification and renamed the language itself to ECMAScript, with JavaScript becoming the commercial implementation of that specification. Ecma International remains the organization that develops and publishes the ECMAScript specification and all the new versions of it, which eventually influence the JavaScript language.

In this section, we read about how JavaScript came to be and performed a quick exercise that showed how it can be examined live within the web browser itself. At this point, you should have a pretty good idea of exactly what JavaScript is, where it came from, and how it operates.

In the next section, we'll look at some more history behind this language by examining the version history of JavaScript beyond ECMA standardization.

 

Versions of ECMAScript (and JavaScript)

With JavaScript now granted Ecma International standardization and the ECMAScript specification, it also needed to follow standard versioning practices. For the first few iterations of the language, this didn't mean much to developers. However, as you will see, as needs grew and the language evolved, major changes would be coming to ECMAScript. They would, in some cases, flow on to JavaScript, and in other cases die altogether.

ECMAScript 1 (1997)

The first version to undergo standardization codified its features more or less from LiveScript. This version is sometimes referred to as ECMAScript First Edition.

It generally corresponds to JavaScript version 1.3.

ECMAScript 2 (1998)

This release saw few changes aside from edits to better conform with established standards. It should probably have been labeled version 1.1.

It also generally corresponds to JavaScript version 1.3.

ECMAScript 3 (1999)

This version of ECMAScript added some fundamental, yet expected (necessary), language enhancements. One of the most important of these is the use of regular expressions (regex), which allows complex pattern matching within text data. The try…catch conditional structure was also introduced, providing an alternative to the more basic if…else statement, allowing more sophisticated error handling. The in operator was also introduced. This generally corresponds to JavaScript version 1.5.

ECMAScript 4 (unreleased)

This release included real classes, modules, generators, static typing, and many language features that were added to the specification many years later.

Note

Eventually, due to committee and corporate infighting, ECMAScript 4 was completely abandoned. Instead, it was replaced with incremental improvements to ECMAScript 3, also known as ECMAScript 3.1.

At this time, Adobe decided to base a complete revision of the ActionScript language (ActionScript 3.0 on this new ECMAScript version. It was an attempt to closely align the language behind the Flash Player and the browsers that commonly hosted it. Here is an example of a basic ActionScript 3.0 class—note that it's quite different from previous versions of ECMAScript:

package com.josephlabrecque {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main() {
// constructor code
}
}
}

ECMAScript 5 (2009)

This version is, in actuality, ECMAScript 3.1, with version 4 completely abandoned. This was more of a politically motived release than anything of substance, though certain bug fixes from ECMAScript 4 were included, along with strict mode, JSON support, and a number of additional methods for working with arrays.

This generally corresponds to JavaScript version 1.8.5 and is the version of JavaScript that conforms to most browsers today.

ECMAScript 6 (2015)

Features including arrow functions, maps, typed-arrays, promises, and many more were introduced with this version of ECMAScript, and many of them form the basis for modern development with JavaScript today. This specification also allows for the writing of classes and modules—finally. The following table explains the browser support for ES6:

Figure 1.2: Browser support table for ECMAScript 2015 via w3schools.com

Figure 1.2: Browser support table for ECMAScript 2015 via w3schools.com

This version of JavaScript is generally SVG supported by modern web browsers and is a major functional release.

ECMAScript 7 (2016), ECMAScript 8 (2017), and ECMAScript 9 (2018)

All versions post2015 have been incremental, with yearly modifications to what was established in ECMAScript 6. This has happened for a number of reasons:

  • It establishes that this is a stable, mature language without the need for major disruption.
  • It allows developers and browser vendors to easily keep up with the changes and enhancements that are adopted.
  • It provides a stable release cycle for new versions of the specification:
Figure 1.3: Browser support table for ECMAScript 2016 via w3schools.com

Figure 1.3: Browser support table for ECMAScript 2016 via w3schools.com

When writing in ECMAScript 2015 (or "ES6") and later, you will likely need to transpile your JavaScript down to a previous version so that it can be understood by the JavaScript engines within the current web browsers. While this is an additional step, the tooling to process tasks such as this has become more approachable in recent years.

Exercise 1.02: Can I Use This Feature?

There is no easy way to tell which versions of JavaScript are supported by which browsers—a more reliable approach is to test whether features you wish to use are supported by the engine currently running the code. Let's take a look at the Can I Use table:

Figure 1.4: "Can I Use" table for ECMAScript 2015 support across browsers

Figure 1.4: "Can I Use" table for ECMAScript 2015 support across browsers

To help us do this, there are a number of resources and services on the web that keep track of JavaScript features and the level of support within each browser. Probably, the most popular of these is the Can I Use table, which includes an abundance of support information around CSS, JavaScript, SVG, HTML5, and more.

Let's go ahead and check out the support for Promise.prototype.finally, which was first implemented in ECMAScript 2018:

  1. Open a web browser and instruct it to load https://packt.live/2WSQhhY. Notice that you have immediate access to the latest and most searched features directly from the home page, without even searching:
    Figure 1.5: The Can I Use website

    Figure 1.5: The Can I Use website

  2. We are looking for something specific, though. Locate the search area toward the top, which reads Can I use ___________?, and type in finally, since we want to see which browsers support Promise.prototype.finally. The results for our search will be displayed automatically within a colored grid:
    Figure 1.6: The grid of browser support for Promise.prototype.finally

    Figure 1.6: The grid of browser support for Promise.prototype.finally

    Note that certain blocks are red, while others are green. A red color indicates that the feature is unsupported, and green indicates that the feature is supported. You may also see a yellow color, indicating partial support.

  3. If you want to see the specifics pertaining to a certain browser version, hover your cursor over the indicated version or version range and a small overlay will appear with additional information such as the date of version release and even usage statistics for that version:
Figure 1.7: Specific support information for Chrome 73

Figure 1.7: Specific support information for Chrome 73

Go ahead and search for additional options within the interface—there is a lot to explore.

In this section, we reviewed the different versions of ECMAScript and looked at how the features of JavaScript, which originated from those particular specifications, are supported within web browsers today.

In the next section, we'll look at how to access the web browser developer tools in order to get a better view of what JavaScript is doing—and even write JavaScript live in the browser.

 

Accessing Web Browser Developer Tools

Our understanding of JavaScript's relationship with the web browser is becoming clearer with each topic that we discuss. In the previous exercise, we saw how to dig in and discover the different levels of JavaScript feature support across different web browsers. That leads us directly to have a look at the various browsers themselves, as well as the tools that are available within each for inspecting and even writing JavaScript code.

Browsers are built to abide by standards such as HTML and CSS. However, there are many differences in both the interpretation of these standards and in the tooling available with each major web browser. When writing JavaScript for the web browser, it is important to know how to access and use the browser developer tools—especially the JavaScript console tab.

Google Chrome

Chrome is the most popular web browser at the time of this writing—this fact holds true for both general users and developers. Chrome was initially released in September 2008 and is now available on multiple desktops and mobile operating systems.

Note

You can download Google Chrome from https://packt.live/2NQRQcn.

To access developer tools and the JavaScript console within Chrome, you can right-click anywhere in the viewport and choose Inspect from the menu that appears. Alternatively, press F12. Once the developer tools are open, click on the Console tab to inspect and write JavaScript code within Chrome itself:

Figure 1.8: Google Chrome Developer Tools

Figure 1.8: Google Chrome Developer Tools

Using the Chrome developer tools, you can filter the sort of things that show errors, warnings, or even just information such as that returned by console.log(). You can even write JavaScript within the browser using the Console tab view, as you'll see shortly. There is also a Sources tab, which allows for modifying and debugging of code.

Microsoft Edge

Having once reigned as the most used web browser in the world, Internet Explorer reached its final version with IE11. This doesn't mean that Microsoft is finished with web browsers though, as, with the release of Windows 10, the newly created Edge browser was made available to users as a replacement in July 2015.

Note

Microsoft Edge comes installed with Windows 10 (https://packt.live/2CnMv6P).

To access the developer tools and the JavaScript console within Edge, you can right-click anywhere in the viewport and choose Inspect Element from the menu that appears. Alternatively, press F12:

Figure 1.9: Microsoft Edge Developer Tools

Figure 1.9: Microsoft Edge Developer Tools

The developer tools in Microsoft Edge are pretty ugly, aren't they? Much like other browsers, Edge's developer tools include a Console and a JavaScript Debugger view. Similar to Chrome, you can also filter the types of output present in the Console itself as your code executes.

Note

As of this writing, Microsoft Edge is being rewritten based on a Chromium base. This will mean that Chrome, Opera, Safari, and Edge will eventually make use of the exact same browser technologies under the hood.

Apple Safari

On Apple macOS and iOS operating systems, Safari is the default web browser and is tightly integrated into the user experience on those machines. Similar to Windows and Internet Explorer/Edge, many users will never deviate from the browser that is preinstalled on their machine.

Safari was once even available on Windows, but development ceased with the final Windows version in 2012.

Note

Apple Safari comes installed with Apple macOS (https://packt.live/32moJTq).

To access the developer tools and the JavaScript console within Safari, you must first tweak some of the preferences within the browser itself. Let's get started:

  1. First, access the preferences dialog by choosing Safari | Preferences through the Application menu.
  2. Within the Preferences dialog, click on the tab called Advanced.
  3. Once the contents of the Advanced tab has appeared, look to the bottom and enable the Show Develop menu in menu bar option:
    Figure 1.10: Apple Safari Advanced Preferences

    Figure 1.10: Apple Safari Advanced Preferences

  4. With that option enabled, close the Preferences dialog.
  5. Now, choose the newly enabled Develop option from the Application menu and select Show JavaScript Console to display the developer tools. You can also right-click and choose Inspect Element as well.

The good news is that once the Develop menu is enabled, it will remain so between sessions. You'll only need to open the developer tools to access these features:

Figure 1.11: Apple Safari Developer Tools

Figure 1.11: Apple Safari Developer Tools

Today, Safari does seem to lag behind most other browsers in adopting certain features, but you will find Apple's version of the Console and Debugger views in the developer tools all the same.

 

An Introduction to Variables

In almost any language, JavaScript included, the first step to programming is to understand the common variable. A variable can be thought of as an identifier for a certain piece of data. To declare a variable in JavaScript, we use the reserved word var:

var name; 

In the preceding example, we declare a variable with the name identifier. Our variable does not have any data associated with it yet. For that, we must use an assignment operator:

name = "Joseph";

Since the variable name has already been declared, we no longer need to use var to declare it in this second step. We simply address the variable by its name and then follow that with an assignment operator of = and then a value, in this case, "Joseph". Of course, you will likely want to use your own name here.

We terminate each line of code with a ; for convention and readability. Note that we can also perform the variable declaration and assignment in a single line of code:

var name = "Joseph";

You now know the foundations of how to declare and assign data values to a variable.

Exercise 1.03: Programming First Steps

Let's go ahead and step through a few bits of JavaScript code within the developer tools console before moving on. If you have your browser developer tools still open from the preceding section. If not, refer to the Accessing Web Browser Developer Tools section of this chapter to access the console.

With the console now available within the web browser, we'll step through a few basic JavaScript declarations:

  1. Within the console, type in the following code and hit Enter:
    var myCity= "London";

    This declares a variable with the identifying name of myCity. This will allow you to invoke this variable later on.

  2. Since this variable is now defined in memory, we can address it whenever we like. Type the following within the console and hit Enter:
    alert("Welcome to " + myCity + "!");

    An alert will pop up over the browser viewport stating, "Welcome to London!". To achieve the full greeting, we will also add additional string information to the variable using concatenation with the + operator. This allows us to mix variable values and plain text data together in our output.

Now you know how to write values to a named variable and how to read those values out by using the variable name.

Activity 1.01: Creating an Alert Box Popup in the Web Browser

In this activity, you will call JavaScript and witness its tight relationship to the web browser. You will learn how to execute an alert within the web browser environment using the browser developer tools.

Note

We'll be using Google Chrome for the following instructions and output images. Other browsers will differ slightly.

Steps:

  1. Press F12 to open the developer tools. Alternatively, a right-click may expose a menu from which you can select Inspect.
  2. Activate the Console tab. The developer tools may default to this view. If not, there is likely a Console tab you can click on to activate it.
  3. Within the console, write the JavaScript command.
  4. Hit Return/Enter to execute the code.

Expected output:

The output should be similar to this:

Figure 1.12: An alert appears with our message

Figure 1.12: An alert appears with our message

Note

The solution to this activity can be found on page 706.

In this section, we had a look at how to access the web browser developer tools across a variety of popular browsers and had a look at some of the different views that can be accessed within.

In the next section, we'll get an overview of exactly what JavaScript is used for and take a general look at the capabilities of the language.

 

Overview of JavaScript Capabilities

Without JavaScript, the web would be a fairly bland and non-interactive experience. As one of the core technologies used to build the web alongside HTML and CSS, JavaScript is immensely important for anyone working with these technologies today. JavaScript allows us to perform complex interactions, ferry data into your application, and display restructured values within web views. It even has the ability to build, destroy, and otherwise modify an entire HTML document.

Client-Side Form Validation

Forms are everywhere on the web—and the HTML specification includes a wide variety of inputs, checkboxes, radio groups, text areas, and more. Often, even before this data hits the server, you'll want to have some logic that looks for certain formatting peculiarities or other aberrations that are present that have been entered by the user. You can trigger initial client-side validation once the Submit button has been clicked, or even as each input loses focus:

Figure 1.13: Form validation on a login

Figure 1.13: Form validation on a login

This is likely one of the most common uses for JavaScript on the web: you can provide basic feedback letting the user know they've done something in error—in this case, invalid login credentials.

JavaScript Widgets or Components

Whether using JavaScript snippets supplied by a component library such as Bootstrap or jQuery UI, or code supplied by specific vendors and services, people have been using JavaScript to include functional widgets and components for over two decades now. It truly is one of the most common uses for JavaScript on the web.

Normally, you are supplied a bit of code that often consists of both HTML and JavaScript. When it is run on the page, there is often either an embedded JavaScript library from which it can call functions, or a remote one, which then transforms the blank slate snippet into a fully functional piece of content for a specific purpose:

Figure 1.14: Embeddable Twitter widget

Figure 1.14: Embeddable Twitter widget

One of the best examples of a JavaScript-based component, or widget, is that of the Twitter timeline embed. You'll find similar embed types for Instagram and other social networks. Nearly all of them use JavaScript to insert dynamic content into a document.

Note

This is different from an <iframe> embed, in that with an <iframe> element, you are simply pulling in content from a remote resource and not building it on the fly.

XML HTTP Requests (XHR)

This technology was born from the concept of Rich Internet Applications (RIA), which has been dominated by technologies such as Adobe Flash Player and Microsoft Silverlight around the turn of the century. What made RIAs great is that you no longer had to refresh the browser view in its entirety in order to see changes in data presented in the browser DOM. Using something such as Flash Player as a visual interactive layer, ActionScript could be used within the application to perform all the tasks related to retrieving data in the background, with the user interface then changes based on the data retrieved. In this way, the user was presented with a much better experience as the entire document wouldn't have to load and reload with every server interaction.

As developers began searching for ways to accomplish this same thing without the use of additional technologies, XMLHttpRequest(XHR) was introduced as part of Microsoft Internet Explorer in 1999 as XMLHTTP. Other browser makers, recognizing the obvious benefits of this implementation, went on to standardize it across their interpretations as XMLHttpRequest.

Note

Previous to this more modern naming, XHR was commonly referred to as Asynchronous JavaScript and XML, abbreviated as AJAX. When people refer to AJAX, they are referring to the XHR API.

Press F12 and navigate to Network | Preview to view the XHR network preview in your browser:

Figure 1.15: XHR network preview in Chrome

Figure 1.15: XHR network preview in Chrome

Browser developer tools all have a way of inspecting the files and data that are being transferred to and from the browser pertaining to the current website. For XHR, you can view raw header information, a formatted preview, and more.

Storing Local Data

Web browsers have been able to store local data for quite some time in the form of cookies. These are generally simple data:value pairs that allow some sort of session memory on the client-side of an application. Eventually, the need arose for much more complex ways of storing local data within the browser as applications grew in complexity.

We now have the LocalStorage API, which was introduced with HTML5, as a more performant, more secure, and more expansive way of storing local website data. You can think of LocalStorage as a better version of cookies all around, yet it still lacks the capabilities of a true database.

If you do need access to a real, client-side database for your web application, you'll want to explore the Indexed Database (IndexedDB) API. IndexedDB is a true client-side database and allows for complex data structures, relationships, and everything you'd expect from a database.

Note

Some web browsers also have access to a Web SQL database as well—but this is no longer considered appropriate by web standards bodies and should generally be avoided.

You can always check the local storage for any website you visit by digging into the developer tools. In Google Chrome, you will find local storage under the Application view:

Figure 1.16: Local storage inspection in Chrome

Figure 1.16: Local storage inspection in Chrome

DOM Manipulation

JavaScript can modify, create, and destroy elements and attributes within the Document Object Model (DOM). This is a very powerful aspect of JavaScript and nearly all modern development frameworks leverage this capability in some way. Similar to XHR, the browser's page doesn't need to be refreshed for us to perform these client-side amendments using JavaScript.

We'll see a particular project based on this in the next chapter, where you'll get some first-hand experience with this very task.

Animations and Effects

Looking back at the web in its infancy, everything was a very static experience. Pages were served up in the browser and consisted of text and hyperlinks. Depending on the year, we usually saw black serif type against a white background with the occasional blue/purple hyperlink.

Eventually, images and different visual stylistic attributes were available, but things really changed with the advent of various extensions such as Macromedia Shockwave and Flash Player. All of a sudden, rich experiences such as interactive video, animation, gaming, audio playback, special effects, and more were all available.

The web standards bodies rightly recognized that all of these capabilities should not be locked behind different browser plugins, but rather be part of the native web experience using core web technologies. Of course, primary among these was JavaScript, though JavaScript often relied on a close relationship with HTML and CSS to make things work. The following screenshot shows an interactive animation created using the CreateJS library:

Figure 1.17: Interactive animation using the CreateJS JavaScript library

Figure 1.17: Interactive animation using the CreateJS JavaScript library

Today, we have rich implementations of the types of content creation that were previously only available with third-party plugins. Libraries such as CreateJS allow for a huge variety of effects, gaming applications, interactions, animations, and beyond and use native JavaScript.

Note

For a number of examples of what is possible in this area of development, have a look at the Google Doodles archive at https://packt.live/2WZafHV.

In this section, we looked at some of the common capabilities of JavaScript that are used on the web today. In the chapters that follow, we'll be exploring some of these capabilities in much greater detail.

 

Summary

In this chapter, we took some time to build a foundation of knowledge that will frame the rest of this book. We began with a historical overview and then examined the relationship between ECMAScript and JavaScript. We then moved on and explored JavaScript by accessing the developer tools of various browsers. Following a hands-on activity and writing a bit of JavaScript with the browser developer tools, we ended this chapter with an overview of JavaScript capabilities. This included DOM manipulation, local data storage, form validation, and other examples to get us into the right mindset when it comes to thinking about the possibilities of working in JavaScript.

In the next chapter, we will explore how to work with JavaScript in much greater detail by using an integrated development environment (IDE) and how to examine the syntax rules of JavaScript. We'll look much more deeply into the web browser as one of a variety of JavaScript runtimes. We'll also explore the use of browser development tools in more detail and get hands on with manipulating both browser elements and additional attributes associated with them.

About the Authors

  • Joseph Labrecque

    Joseph Labrecque is a creative developer, designer, and educator with over 15 years of experience building expressive web, desktop, and mobile solutions. Over the past decade, Joseph has authored several books, articles, and video course publications on design and development technologies, tools, and concepts through publishers such as Lynda, LinkedIn Learning, Peachpit, Pluralsight, and Adobe.

    Browse publications by this author
  • Jahred Love

    Jahred Love is a co-founder and CTO of Xirsys LLC, CPO of Millicast, co-founder and CTO of Innov8Estate and CTO of PLP London. A serial entrepreneur, Jahred has been a software engineer working with JavaScript for the last 20 years, building everything from games and applications to distributed real-time platforms and Internet of Things (IoT) devices.

    Browse publications by this author
  • Daniel Rosenbaum

    Daniel Rosenbaum has more than 20 years of experience as a solutions architect, technical lead, and developer with a demonstrated history of working in information technology for health and financial services. He is a strong engineering professional skilled in enterprise architecture and agile software development of many web-based and back-end data systems.

    Browse publications by this author
  • Nick Turner

    Nick Turner is a software engineer and life-long technology enthusiast. He specializes in building web, mobile, and desktop applications using modern JavaScript frameworks. An advocate of distributed teams, Nick runs a small software company helping its clients to launch exciting, transformative products out into the world.

    Browse publications by this author
  • Gaurav Mehla

    Gaurav Mehla is a full-stack developer who has built web, desktop, and hybrid mobile applications on JavaScript. He has 8 years of solid JavaScript experience. He is currently leading a very productive team in a startup.

    Browse publications by this author
  • Alonzo L. Hosford

    Alonzo L. Hosford is a website developer, trainer, and author. He is the founder CEO of Click Systems Consulting, LLC specializing in WordPress websites and of the Web Skills Bootcamp teaching web developer skill courses. Alonzo is an assistant adjunct professor and curriculum creator of web technology at Raritan Valley Community College.

    Browse publications by this author
  • Florian Sloot

    Florian Sloot is a tech-lover since childhood and during his development years, he learned the importance of teaching and guiding. Therefore, as he got some experience with building applications, he started publishing learning resources himself. To date, he has taught hundreds of students and co-workers.

    Browse publications by this author
  • Philip Kirkbride

    Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.

    Browse publications by this author

Latest Reviews

(5 reviews total)
good
The arguments are clearly explained
Good book, well structured

Recommended For You

Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial