Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
The JavaScript Workshop
The JavaScript Workshop

The JavaScript Workshop: Learn to develop interactive web applications with clean and maintainable JavaScript code

Arrow left icon
Profile Icon Joseph Labrecque Profile Icon Alonzo L. Hosford Profile Icon Gaurav Mehla Profile Icon Nick Turner Profile Icon Daniel Rosenbaum Profile Icon Jahred Love Profile Icon Florian Sloot Profile Icon Philip Kirkbride +4 more Show less
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (8 Ratings)
eBook Nov 2019 802 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Joseph Labrecque Profile Icon Alonzo L. Hosford Profile Icon Gaurav Mehla Profile Icon Nick Turner Profile Icon Daniel Rosenbaum Profile Icon Jahred Love Profile Icon Florian Sloot Profile Icon Philip Kirkbride +4 more Show less
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (8 Ratings)
eBook Nov 2019 802 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

The JavaScript Workshop

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 for this activity can be found via this link.

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn the basics of JavaScript programming to create dynamic web pages
  • Explore the fundamentals of back-end development using Node.js
  • Tackle challenging development problems and apply solutions to real-world situations

Description

If you're looking for a programming language to develop flexible and efficient apps, JavaScript is a great choice. However, while offering real benefits, the complexity of the entire JavaScript ecosystem can be overwhelming. This Workshop is a smarter way to learn JavaScript. It is specifically designed to cut through the noise and help build your JavaScript skills from scratch, while sparking your interest with engaging activities and clear explanations. Starting with explanations of JavaScript's fundamental programming concepts, this book will introduce the key tools, libraries and frameworks that programmers use in everyday development. You will then move on and see how to handle data, control the flow of information in an application, and create custom events. You'll explore the differences between client-side and server-side JavaScript, and expand your knowledge further by studying the different JavaScript development paradigms, including object-oriented and functional programming. By the end of this JavaScript book, you'll have the confidence and skills to tackle real-world JavaScript development problems that reflect the emerging requirements of the modern web.

Who is this book for?

The JavaScript Workshop is the ideal guide to JavaScript for beginners. It is designed for anyone who wants to get started learning JavaScript. Whether you're an aspiring web developer, or are just curious about learning how to code with a versatile programming language, this book will help you get up and running. Previous development experience is not required, but basic prior knowledge of HTML and CSS will help you get the most from this book.

What you will learn

  • Write clean, maintainable and eloquent JavaScript code
  • Build websites using plain JS and various frameworks and libraries
  • Simplify your workflow with package managers such as Gulp and Grunt
  • Use Node.js to build server-side JavaScript applications
  • Improve the functionality of your applications with browser APIs
  • Implement asynchronous programming to build apps that can multitask

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 29, 2019
Length: 802 pages
Edition : 1st
Language : English
ISBN-13 : 9781838645885
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 29, 2019
Length: 802 pages
Edition : 1st
Language : English
ISBN-13 : 9781838645885
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
The Python Workshop
€47.99
The JavaScript Workshop
€32.99
The HTML and CSS Workshop
€29.99
Total 110.97 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Getting to Know JavaScript Chevron down icon Chevron up icon
2. Working with JavaScript Chevron down icon Chevron up icon
3. Programming Fundamentals Chevron down icon Chevron up icon
4. JavaScript Libraries and Frameworks Chevron down icon Chevron up icon
5. Beyond the Fundamentals Chevron down icon Chevron up icon
6. Understanding Core Concepts Chevron down icon Chevron up icon
7. Popping the Hood Chevron down icon Chevron up icon
8. Browser APIs Chevron down icon Chevron up icon
9. Working with Node.js Chevron down icon Chevron up icon
10. Accessing External Resources Chevron down icon Chevron up icon
11. Creating Clean and Maintainable Code Chevron down icon Chevron up icon
12. Using NextGeneration JavaScript Chevron down icon Chevron up icon
13. JavaScript Programming Paradigms Chevron down icon Chevron up icon
14. Understanding Functional Programming Chevron down icon Chevron up icon
15. Asynchronous Tasks Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(8 Ratings)
5 star 75%
4 star 0%
3 star 0%
2 star 0%
1 star 25%
Filter icon Filter
Top Reviews

Filter reviews by




david griffin Aug 02, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been writing JavaScript code for a couple of years now and I have to say this book is COMPREHENSIVE to say the least. I learned something new every chapter. This is a long book but well worth the read if you are a dev or an aspiring dev. I look forward to reading again soon!
Amazon Verified review Amazon
shahriyar Jun 02, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you would like to get familiar with JavaScript from entry level and gain some real world experience and useful content, this book is recommended for you! Don't worry if you have no idea of web developing tools or even installation steps; This book is a self guide and easy to understand.
Amazon Verified review Amazon
Mark kho May 27, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I enjoyed reading the JavaScript Workshop. It's a good book for people who would like to learn the fundamentals and also some advanced concepts. If you are in search of a book that will help learn Javascript, this is the book for you!
Amazon Verified review Amazon
K. Skelton May 27, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I received an e-book copy of this title in exchange for a review. I have been a teaching assistant at code bootcamps as well as in university courses, and I am a full-time professional software engineer.I recommend this book for self learners as well as folks who need a refresher on modern JavaScript. The chapters are well designed: they're dense without being overwhelming; they are well organized with easy to find topics; the examples are typically something that might be part of a larger application. The first chapter is an overview of the history of JS and how it fits into software development as a whole. It sets the tone that the authors want you to explore code and do so using HTML, CSS and JS without over explaining what's going on. You need to trust that the authors will fill in these blanks and from a teaching perspective they're establishing the context of what can be done with the material (code); to use a fishing metaphor they're setting the hook.The remaining chapters cover JS topics, though in such a way that the engineering/science principles are being taught in parallel with the code syntax. Understanding flow control and iterators is core to all programming and those concepts are as well explained as the JS code that makes it happen. In the case where a built-in object is discussed ("Date" comes to mind) the authors include handy tables that include the properties on the object and what it does. Example - Method: getDay() Description: Get the weekday as a number from 0 to 6.Each chapter has several code exercises/examples which I found to be extremely thorough. The jaded might call the examples hand-holding. But for the learner who is new I think having explicit step-by-step instructions and screenshots (as well as information about what should happen with each step) will be very valuable.There is a lot of competition in coding books at this price point. I think this would be a very good investment.
Amazon Verified review Amazon
Amazon Customer Nov 05, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Completed the online JavaScript Workshop and enjoyed it. I have been developing with JavaScript on and off for the past 20 years but wanted to brush up on modern JavaScript development.I found the workshop a good overview of JavaScript. It goes into each topic enough so you have a basic grasp of the functionality and know enough to dive in deeper by yourself.The pacing of the workshop is fast and you need to absorb lots of information but I liked that.Not sure this is the best course for an absolute beginner at JavaScript. Would recommend it for developers who have some JavaScript experience but want to build on that and develop their skills further.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.