JavaScript - Inc Publishing - E-Book

JavaScript E-Book

Inc Publishing

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book provides a comprehensive introduction to JavaScript and web development, starting with the basics of programming and progressing through advanced topics. The initial chapters introduce JavaScript, exploring its history, its relationship with HTML and CSS, and how to integrate it into web pages. Readers will learn to create and manipulate variables, data types, and operators while controlling the flow of programs using loops and functions.
As the book advances, it covers more complex concepts like working with objects, arrays, and strings, and introduces modern web APIs, such as Ajax, Fetch API, and browser storage methods. Additional chapters focus on object-oriented and functional programming, emphasizing JavaScript’s versatile capabilities.
Later sections explore asynchronous programming, server-based applications with Node.js, and creating mobile and desktop applications using frameworks like React Native and Electron. There is also a focus on controlling microcontrollers using JavaScript, automating tasks with Grunt and Gulp, and managing source code through Git, providing a full-stack development approach with JavaScript at its core.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 1276

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Philip Ackermann

JavaScript

The Comprehensive Guide

Imprint

This e-book is a publication many contributed to, specifically:

Editor   Hareem ShafiGerman Edition Editor   Patricia SchiewaldGerman Edition Technical Reviewer   Sebastian SpringerCopyeditor   Melinda RankinTranslation   Winema Language Services, Inc.Cover Design   Graham Geary    AdobeStock: 137196969/© Studio PeaceProduction E-Book   Hannah LaneTypesetting E-Book   Satz-Pro, Germany

We hope that you liked this e-book. Please share your feedback with us and read the Service Pages to find out how to contact us.

The Library of Congress has cataloged the printed edition as follows: Names: Ackermann, Philipp, author. Title: JavaScript : the comprehensive guide / by Philip Ackermann. Description: 1st edition. | Bonn ; Boston : Rheinwerk Publishing, 2022. | Includes index. Identifiers: LCCN 2022023983 | ISBN 9781493222865 (hardcover) | ISBN 9781493222872 (ebook) Subjects: LCSH: JavaScript (Computer program language) | Computer programming. | Web site development. Classification: LCC QA76.73.J39 A26 2022 | DDC 005.2/762--dc23/eng/20220729 LC record available at https://lccn.loc.gov/2022023983

ISBN 978-1-4932-2286-5 (print)ISBN 978-1-4932-2287-2 (e-book)ISBN 978-1-4932-2288-9 (print and e-book)

© 2022 by Rheinwerk Publishing Inc., Boston (MA)1st edition 20223rd German edition published 2021 by Rheinwerk Verlag, Bonn, Germany

Dear Reader,

For as long as I can remember, I have wanted to learn to drive.

Due to an assortment of life events, I didn’t get the opportunity to get my license until a few years ago, at 28. I hopped into the instructor’s car on the day of my first lesson, drove through an intersection, made four right turns, parked haphazardly, and hobbled out of the car and to my front door, stiff with fear. Everything had gone well. But at the first traffic light, watching cars race past, I’d had an epiphany: cars were accursed death traps. I canceled my remaining lessons.

A year passed before I signed up again. When I relayed my previous experience to my new instructor, he, a college student working part time at the driving school, nodded knowingly. His adult drivers were often more anxious learners than his teenage pupils. “You overthink it,” he noted. “Also, your brains are too developed. More impulse control, less risky behavior.” (Here he shook his head regrettably, as if to say that a fully developed brain was an unfortunate characteristic to possess.) “You need to get out of your own way. Let yourself be a little reckless.”

Reader, I did get out of my own way. I successfully learned to drive that year and I’m pleased to say that I love it. And I often find myself returning to my instructor’s advice. When I think about adopting new hobbies or learning new skills, I do my best to learn without restraint.

Whether you have picked up this book for passion or practicality, whether you are a beginner or an experienced programmer, I hope you find similar success learning about JavaScript. Your driving instructor is expert author Philip Ackermann, who has written a meticulous manual to guide you on your JavaScript journey, from language basics to client-side and server-side programming.

What did you think about JavaScript: The Comprehensive Guide? Your comments and suggestions are the most useful tools to help us make our books the best they can be. Please feel free to contact me and share any praise or criticism you may have.

Thank you for purchasing a book from Rheinwerk Publishing!

Hareem ShafiEditor, Rheinwerk Publishing

hareems@rheinwerk-publishing.comwww.rheinwerk-computing.comRheinwerk Publishing • Boston, MA

Notes on Usage

This e-book is protected by copyright. By purchasing this e-book, you have agreed to accept and adhere to the copyrights. You are entitled to use this e-book for personal purposes. You may print and copy it, too, but also only for personal use. Sharing an electronic or printed copy with others, however, is not permitted, neither as a whole nor in parts. Of course, making them available on the internet or in a company network is illegal as well.

For detailed and legally binding usage conditions, please refer to the section Legal Notes.

This e-book copy contains a digital watermark, a signature that indicates which person may use this copy:

Notes on the Screen Presentation

You are reading this e-book in a file format (EPUB or Mobi) that makes the book content adaptable to the display options of your reading device and to your personal needs. That’s a great thing; but unfortunately not every device displays the content in the same way and the rendering of features such as pictures and tables or hyphenation can lead to difficulties. This e-book was optimized for the presentation on as many common reading devices as possible.

If you want to zoom in on a figure (especially in iBooks on the iPad), tap the respective figure once. By tapping once again, you return to the previous screen. You can find more recommendations on the customization of the screen layout on the Service Pages.

Table of Contents

Dear Reader

Notes on Usage

Table of Contents

Book Resources

Preface

1   Basics and Introduction

1.1   Programming Basics

1.1.1   Communicating with the Computer

1.1.2   Programming Languages

1.1.3   Tools for Program Design

1.2   Introduction to JavaScript

1.2.1   History

1.2.2   Fields of Application

1.3   Summary

2   Getting Started

2.1   Introduction to JavaScript and Web Development

2.1.1   The Relationship among HTML, CSS, and JavaScript

2.1.2   The Right Tool for Development

2.2   Integrating JavaScript into a Web Page

2.2.1   Preparing a Suitable Folder Structure

2.2.2   Creating a JavaScript File

2.2.3   Embedding a JavaScript File in an HTML File

2.2.4   Defining JavaScript Directly within the HTML

2.2.5   Placement and Execution of the <script> Elements

2.2.6   Displaying the Source Code

2.3   Creating Output

2.3.1   Showing the Standard Dialog Window

2.3.2   Writing to the Console

2.3.3   Using Existing UI Components

2.4   Summary

3   Language Core

3.1   Storing Values in Variables

3.1.1   Defining Variables

3.1.2   Using Valid Variable Names

3.1.3   Defining Constants

3.2   Using the Different Data Types

3.2.1   Numbers

3.2.2   Strings

3.2.3   Boolean Values

3.2.4   Arrays

3.2.5   Objects

3.2.6   Special Data Types

3.2.7   Symbols

3.3   Deploying the Different Operators

3.3.1   Operators for Working with Numbers

3.3.2   Operators for Easier Assignment

3.3.3   Operators for Working with Strings

3.3.4   Operators for Working with Boolean Values

3.3.5   Operators for Working with Bits

3.3.6   Operators for Comparing Values

3.3.7   The Optional Chaining Operator

3.3.8   The Logical Assignment Operators

3.3.9   Operators for Special Operations

3.4   Controlling the Flow of a Program

3.4.1   Defining Conditional Statements

3.4.2   Defining Branches

3.4.3   Using the Selection Operator

3.4.4   Defining Multiway Branches

3.4.5   Defining Counting Loops

3.4.6   Defining Head-Controlled Loops

3.4.7   Defining Tail-Controlled Loops

3.4.8   Prematurely Terminating Loops and Loop Iterations

3.5   Creating Reusable Code Blocks

3.5.1   Defining Functions

3.5.2   Calling Functions

3.5.3   Passing and Evaluating Function Parameters

3.5.4   Defining Return Values

3.5.5   Defining Default Values for Parameters

3.5.6   Using Elements from an Array as Parameters

3.5.7   Defining Functions Using Short Notation

3.5.8   Modifying Strings via Functions

3.5.9   Functions in Detail

3.5.10   Calling Functions through User Interaction

3.6   Responding to Errors and Handling Them Correctly

3.6.1   Syntax Errors

3.6.2   Runtime Errors

3.6.3   Logic Errors

3.6.4   The Principle of Error Handling

3.6.5   Catching and Handling Errors

3.6.6   Triggering Errors

3.6.7   Errors and the Function Call Stack

3.6.8   Calling Certain Statements Regardless of Errors That Have Occurred

3.7   Commenting the Source Code

3.8   Debugging the Code

3.8.1   Introduction

3.8.2   A Simple Code Example

3.8.3   Defining Breakpoints

3.8.4   Viewing Variable Assignments

3.8.5   Running a Program Step by Step

3.8.6   Defining Multiple Breakpoints

3.8.7   Other Types of Breakpoints

3.8.8   Viewing the Function Call Stack

3.9   Summary

4   Working with Reference Types

4.1   Difference between Primitive Data Types and Reference Types

4.1.1   The Principle of Primitive Data Types

4.1.2   The Principle of Reference Types

4.1.3   Primitive Data Types and Reference Types as Function Arguments

4.1.4   Determining the Type of a Variable

4.1.5   Outlook

4.2   Encapsulating State and Behavior in Objects

4.2.1   Introduction to Object-Oriented Programming

4.2.2   Creating Objects Using Literal Notation

4.2.3   Creating Objects via Constructor Functions

4.2.4   Creating Objects Using Classes

4.2.5   Creating Objects via the Object.create() Function

4.2.6   Accessing Properties and Calling Methods

4.2.7   Adding or Overwriting Object Properties and Object Methods

4.2.8   Deleting Object Properties and Object Methods

4.2.9   Outputting Object Properties and Object Methods

4.2.10   Using Symbols to Define Unique Object Properties

4.2.11   Preventing Changes to Objects

4.3   Working with Arrays

4.3.1   Creating and Initializing Arrays

4.3.2   Accessing Elements of an Array

4.3.3   Adding Elements to an Array

4.3.4   Removing Elements from an Array

4.3.5   Copying Some of the Elements from an Array

4.3.6   Sorting Arrays

4.3.7   Using Arrays as a Stack

4.3.8   Using Arrays as a Queue

4.3.9   Finding Elements in Arrays

4.3.10   Copying Elements within an Array

4.3.11   Converting Arrays to Strings

4.4   Extracting Values from Arrays and Objects

4.4.1   Extracting Values from Arrays

4.4.2   Extracting Values from Objects

4.4.3   Extracting Values within a Loop

4.4.4   Extracting Arguments of a Function

4.4.5   Copying Object Properties to Another Object

4.4.6   Copying Object Properties from Another Object

4.5   Working with Strings

4.5.1   The Structure of a String

4.5.2   Determining the Length of a String

4.5.3   Searching within a String

4.5.4   Extracting Parts of a String

4.6   Using Maps

4.6.1   Creating Maps

4.6.2   Basic Operations

4.6.3   Iterating over Maps

4.6.4   Using Weak Maps

4.7   Using Sets

4.7.1   Creating Sets

4.7.2   Basic Operations of Sets

4.7.3   Iterating over Sets

4.7.4   Using Weak Sets

4.8   Other Global Objects

4.8.1   Working with Date and Time Information

4.8.2   Performing Complex Calculations

4.8.3   Wrapper Objects for Primitive Data Types

4.9   Working with Regular Expressions

4.9.1   Defining Regular Expressions

4.9.2   Testing Characters against a Regular Expression

4.9.3   Using Character Classes

4.9.4   Limiting Beginning and End

4.9.5   Using Quantifiers

4.9.6   Searching for Occurrences

4.9.7   Searching All Occurrences within a String

4.9.8   Accessing Individual Parts of an Occurrence

4.9.9   Searching for Specific Strings

4.9.10   Replacing Occurrences within a String

4.9.11   Searching for Occurrences

4.9.12   Splitting Strings

4.10   Functions as Reference Types

4.10.1   Using Functions as Arguments

4.10.2   Using Functions as Return Values

4.10.3   Standard Methods of Each Function

4.11   Summary

5   Dynamically Changing Web Pages

5.1   Structure of a Web Page

5.1.1   Document Object Model

5.1.2   The Different Types of Nodes

5.1.3   The Document Node

5.2   Selecting Elements

5.2.1   Selecting Elements by ID

5.2.2   Selecting Elements by Class

5.2.3   Selecting Elements by Element Name

5.2.4   Selecting Elements by Name

5.2.5   Selecting Elements by Selector

5.2.6   Selecting the Parent Element of an Element

5.2.7   Selecting the Child Elements of an Element

5.2.8   Selecting the Sibling Elements of an Element

5.2.9   Calling Selection Methods on Elements

5.2.10   Selecting Elements by Type

5.3   Working with Text Nodes

5.3.1   Accessing the Text Content of an Element

5.3.2   Modifying the Text Content of an Element

5.3.3   Modifying the HTML below an Element

5.3.4   Creating and Adding Text Nodes

5.4   Working with Elements

5.4.1   Creating and Adding Elements

5.4.2   Removing Elements and Nodes

5.4.3   The Different Types of HTML Elements

5.5   Working with Attributes

5.5.1   Reading the Value of an Attribute

5.5.2   Changing the Value of an Attribute or Adding a New Attribute

5.5.3   Creating and Adding Attribute Nodes

5.5.4   Removing Attributes

5.5.5   Accessing CSS classes

5.6   Summary

6   Processing and Triggering Events

6.1   The Concept of Event-Driven Programming

6.2   Responding to Events

6.2.1   Defining an Event Handler via HTML

6.2.2   Defining an Event Handler via JavaScript

6.2.3   Defining Event Listeners

6.2.4   Defining Multiple Event Listeners

6.2.5   Passing Arguments to Event Listeners

6.2.6   Removing Event Listeners

6.2.7   Defining Event Handlers and Event Listeners via a Helper Function

6.2.8   Accessing Information of an Event

6.3   The Different Types of Events

6.3.1   Events when Interacting with the Mouse

6.3.2   Events when Interacting with the Keyboard and with Text Fields

6.3.3   Events when Working with Forms

6.3.4   Events when Focusing Elements

6.3.5   General Events of the User Interface

6.3.6   Events on Mobile Devices

6.4   Understanding and Influencing the Flow of Events

6.4.1   The Event Phases

6.4.2   Interrupting the Event Flow

6.4.3   Preventing Default Actions of Events

6.5   Programmatically Triggering Events

6.5.1   Triggering Simple Events

6.5.2   Triggering Events with Passed Arguments

6.5.3   Triggering Default Events

6.6   Summary

7   Working with Forms

7.1   Accessing Forms and Form Fields

7.1.1   Accessing Forms

7.1.2   Accessing Form Elements

7.1.3   Reading the Value of Text Fields and Password Fields

7.1.4   Reading the Value of Checkboxes

7.1.5   Reading the Value of Radio Buttons

7.1.6   Reading the Value of Selection Lists

7.1.7   Reading the Values of Multiple Selection Lists

7.1.8   Populating Selection Lists with Values Using JavaScript

7.2   Programmatically Submitting and Resetting Forms

7.3   Validating Form Inputs

7.4   Summary

8   Controlling Browsers and Reading Browser Information

8.1   The Browser Object Model

8.2   Accessing Window Information

8.2.1   Determining the Size and Position of a Browser Window

8.2.2   Changing the Size and Position of a Browser Window

8.2.3   Accessing Display Information of the Browser Bars

8.2.4   Determining General Properties

8.2.5   Opening New Browser Windows

8.2.6   Closing the Browser Window

8.2.7   Opening Dialogs

8.2.8   Executing Functions in a Time-Controlled Manner

8.3   Accessing Navigation Information of a Currently Open Web Page

8.3.1   Accessing the Individual Components of the URL

8.3.2   Accessing Query String Parameters

8.3.3   Loading a New Web Page

8.4   Viewing and Modifying the Browsing History

8.4.1   Navigating in the Browsing History

8.4.2   Browsing History for Single-Page Applications

8.4.3   Adding Entries to the Browsing History

8.4.4   Responding to Changes in the Browsing History

8.4.5   Replacing the Current Entry in the Browsing History

8.5   Recognizing Browsers and Determining Browser Features

8.6   Accessing Screen Information

8.7   Summary

9   Dynamically Reloading Contents of a Web Page

9.1   The Principle of Ajax

9.1.1   Synchronous Communication

9.1.2   Asynchronous Communication

9.1.3   Typical Use Cases for Ajax

9.1.4   Data Formats Used

9.2   The XML Format

9.2.1   The Structure of XML

9.2.2   XML and the DOM API

9.2.3   Converting Strings to XML Objects

9.2.4   Converting XML Objects to Strings

9.3   The JSON Format

9.3.1   The Structure of JSON

9.3.2   Difference between JSON and JavaScript Objects

9.3.3   Converting Objects to JSON Format

9.3.4   Converting Objects from JSON Format

9.4   Making Requests via Ajax

9.4.1   The XMLHttpRequest Object

9.4.2   Loading HTML Data via Ajax

9.4.3   Loading XML Data via Ajax

9.4.4   Loading JSON Data via Ajax

9.4.5   Sending Data to the Server via Ajax

9.4.6   Submitting Dorms via Ajax

9.4.7   Loading Data from Other Domains

9.4.8   The Newer Alternative to XMLHttpRequest: The Fetch API

9.5   Summary

10   Simplifying Tasks with jQuery

10.1   Introduction

10.1.1   Embedding jQuery

10.1.2   Embedding jQuery via a Content Delivery Network

10.1.3   Using jQuery

10.1.4   Simplifying Tasks with jQuery

10.2   Working with the DOM

10.2.1   Selecting Elements

10.2.2   Accessing and Modifying Content

10.2.3   Filtering Selected Elements

10.2.4   Accessing Attributes

10.2.5   Accessing CSS Properties

10.2.6   Navigating between Elements

10.2.7   Using Effects and Animations

10.3   Responding to Events

10.3.1   Registering Event Listeners

10.3.2   Responding to General Events

10.3.3   Responding to Mouse Events

10.3.4   Responding to Keyboard Events

10.3.5   Responding to Form Events

10.3.6   Accessing Information from Events

10.4   Creating Ajax Requests

10.4.1   Creating Ajax Requests

10.4.2   Responding to Events

10.4.3   Loading HTML Data via Ajax

10.4.4   Loading XML Data via Ajax

10.4.5   Loading JSON Data via Ajax

10.5   Summary

11   Dynamically Creating Images and Graphics

11.1   Drawing Images

11.1.1   The Drawing Area

11.1.2   The Rendering Context

11.1.3   Drawing Rectangles

11.1.4   Using Paths

11.1.5   Drawing Texts

11.1.6   Drawing Gradients

11.1.7   Saving and Restoring the Canvas State

11.1.8   Using Transformations

11.1.9   Creating Animations

11.2   Integrating Vector Graphics

11.2.1   The SVG Format

11.2.2   Integrating SVG in HTML

11.2.3   Changing the Appearance of SVG Elements with CSS

11.2.4   Manipulating the Behavior of SVG Elements via JavaScript

11.3   Summary

12   Using Modern Web APIs

12.1   Communicating via JavaScript

12.1.1   Unidirectional Communication with the Server

12.1.2   Bidirectional Communication with a Server

12.1.3   Outgoing Communication from the Server

12.2   Recognizing Users

12.2.1   Using Cookies

12.2.2   Creating Cookies

12.2.3   Reading Cookies

12.2.4   Example: Shopping Cart Based on Cookies

12.2.5   Disadvantages of Cookies

12.3   Using the Browser Storage

12.3.1   Storing Values in the Browser Storage

12.3.2   Reading Values from the Browser Storage

12.3.3   Updating Values in the Browser Storage

12.3.4   Deleting Values from the Browser Storage

12.3.5   Responding to Changes in the Browser Storage

12.3.6   The Different Types of Browser Storage

12.3.7   Example: Shopping Cart Based on the Browser Storage

12.4   Using the Browser Database

12.4.1   Opening a Database

12.4.2   Creating a Database

12.4.3   Creating an Object Store

12.4.4   Adding Objects to an Object Store

12.4.5   Reading Objects from an Object Store

12.4.6   Deleting Objects from an Object Store

12.4.7   Updating Objects in an Object Store

12.4.8   Using a Cursor

12.5   Accessing the File System

12.5.1   Selecting Files via File Dialog

12.5.2   Selecting Files via Drag and Drop

12.5.3   Reading Files

12.5.4   Monitoring the Reading Progress

12.6   Moving Components of a Web Page

12.6.1   Events of a Drag-and-Drop Operation

12.6.2   Defining Movable Elements

12.6.3   Moving Elements

12.7   Parallelizing Tasks

12.7.1   The Principle of Web Workers

12.7.2   Use Web Workers

12.8   Determining the Location of Users

12.8.1   Accessing Location Information

12.8.2   Continuously Accessing Location Information

12.8.3   Showing the Position on a Map

12.8.4   Showing Directions

12.9   Reading the Battery Level of an End Device

12.9.1   Accessing Battery Information

12.9.2   Responding to Events

12.10   Outputting Speech and Recognizing Speech

12.10.1   Outputting Speech

12.10.2   Recognizing Speech

12.11   Creating Animations

12.11.1   Using the API

12.11.2   Controlling an Animation

12.12   Working with the Command Line

12.12.1   Selecting and Inspecting DOM Elements

12.12.2   Events Analysis

12.12.3   Debugging, Monitoring, and Profiling

12.13   Developing Multilingual Applications

12.13.1   Explanation of Terms

12.13.2   The Internationalization API

12.13.3   Comparing Character String Expressions

12.13.4   Formatting Dates and Times

12.13.5   Formatting Numeric Values

12.14   Overview of Various Web APIs

12.15   Summary

13   Object-Oriented Programming

13.1   The Principles of Object-Oriented Programming

13.1.1   Classes, Object Instances, and Prototypes

13.1.2   Principle 1: Define Abstract Behavior

13.1.3   Principle 2: Encapsulate Condition and Behavior

13.1.4   Principle 3: Inherit Condition and Behavior

13.1.5   Principle 4: Accept Different Types

13.1.6   JavaScript and Object Orientation

13.2   Prototypical Object Orientation

13.2.1   The Concept of Prototypes

13.2.2   Deriving from Objects

13.2.3   Inheriting Methods and Properties

13.2.4   Defining Methods and Properties in the Inheriting Object

13.2.5   Overwriting Methods

13.2.6   The Prototype Chain

13.2.7   Calling Methods of the Prototype

13.2.8   Prototypical Object Orientation and the Principles of Object Orientation

13.3   Pseudoclassical Object Orientation

13.3.1   Defining Constructor Functions

13.3.2   Creating Object Instances

13.3.3   Defining Methods

13.3.4   Deriving from Objects

13.3.5   Calling the Constructor of the "Superclass"

13.3.6   Overwriting Methods

13.3.7   Calling Methods of the "Superclass"

13.3.8   Pseudoclassical Object Orientation and the Principles of Object Orientation

13.4   Object Orientation with Class Syntax

13.4.1   Defining Classes

13.4.2   Creating Object Instances

13.4.3   Defining Getters and Setters

13.4.4   Defining Private Properties and Private Methods

13.4.5   Deriving from "Classes"

13.4.6   Overwriting Methods

13.4.7   Calling Methods of the "Superclass"

13.4.8   Defining Static Methods

13.4.9   Defining Static Properties

13.4.10   Class Syntax and the Principles of Object Orientation

13.5   Summary

14   Functional Programming

14.1   Principles of Functional Programming

14.2   Imperative Programming and Functional Programming

14.2.1   Iterating with the forEach() Method

14.2.2   Mapping Values with the map() Method

14.2.3   Filtering Values with the filter() Method

14.2.4   Reducing Multiple Values to One Value with the reduce() Method

14.2.5   Combination of the Different Methods

14.3   Summary

15   Correctly Structuring the Source Code

15.1   Avoiding Name Conflicts

15.2   Defining and Using Modules

15.2.1   The Module Design Pattern

15.2.2   The Revealing Module Design Pattern

15.2.3   AMD

15.2.4   CommonJS

15.2.5   Native Modules

15.3   Summary

16   Using Asynchronous Programming and Other Advanced Features

16.1   Understanding and Using Asynchronous Programming

16.1.1   Using the Callback Design Pattern

16.1.2   Using Promises

16.1.3   Using Async Functions

16.2   Encapsulating Iteration over Data Structures

16.2.1   The Principle of Iterators

16.2.2   Using Iterators

16.2.3   Creating Your Own Iterator

16.2.4   Creating an Iterable Object

16.2.5   Iterating over Iterable Objects

16.3   Pausing and Resuming Functions

16.3.1   Creating a Generator Function

16.3.2   Creating a Generator

16.3.3   Iterating over Generators

16.3.4   Creating Infinite Generators

16.3.5   Controlling Generators with Parameters

16.4   Intercepting Access to Objects

16.4.1   The Principle of Proxies

16.4.2   Creating Proxies

16.4.3   Defining Handlers for Proxies

16.5   Summary

17   Creating Server-Based Applications with Node.js

17.1   Introduction to Node.js

17.1.1   The Architecture of Node.js

17.1.2   Installing Node.js

17.1.3   A Simple Application

17.2   Managing Node.js Packages

17.2.1   Installing the Node.js Package Manager

17.2.2   Installing Packages

17.2.3   Creating Your Own Packages

17.3   Processing and Triggering Events

17.3.1   Triggering and Intercepting an Event

17.3.2   Triggering an Event Multiple Times

17.3.3   Intercepting an Event Exactly Once

17.3.4   Intercepting an Event Multiple Times

17.4   Accessing the File System

17.4.1   Reading Files

17.4.2   Writing Files

17.4.3   Reading File Information

17.4.4   Deleting Files

17.4.5   Working with Directories

17.5   Creating a Web Server

17.5.1   Starting a Web Server

17.5.2   Making Files Available via Web Server

17.5.3   Creating a Client for a Web Server

17.5.4   Defining Routes

17.5.5   Using the Express.js Web Framework

17.6   Accessing Databases

17.6.1   MongoDB Installation

17.6.2   Installing a MongoDB Driver for Node.js

17.6.3   Establishing a Connection to the Database

17.6.4   Creating a Collection

17.6.5   Saving Objects

17.6.6   Reading Objects

17.6.7   Updating Objects

17.6.8   Deleting Objects

17.7   Working with Streams

17.7.1   Introduction and Types of Streams

17.7.2   Stream Use Cases

17.7.3   Reading Data with Streams

17.7.4   Writing Data with Streams

17.7.5   Combining Streams Using Piping

17.7.6   Error Handling during Piping

17.8   Summary

18   Creating Mobile Applications with JavaScript

18.1   The Different Types of Mobile Applications

18.1.1   Native Applications

18.1.2   Mobile Web Applications

18.1.3   Hybrid Applications

18.1.4   Comparison of the Different Approaches

18.2   Creating Mobile Applications with React Native

18.2.1   The Principle of React Native

18.2.2   Installation and Project Initialization

18.2.3   Starting the Application

18.2.4   The Basic Structure of a React Native Application

18.2.5   Using UI Components

18.2.6   Communication with the Server

18.2.7   Building and Publishing Applications

18.3   Summary

19   Desktop Applications with JavaScript

19.1   NW.js

19.1.1   Installing and Creating an Application

19.1.2   Starting the Application

19.1.3   Packaging of the Application

19.1.4   More Sample Applications

19.2   Electron

19.2.1   Installing and Creating an Application

19.2.2   Starting the Application

19.2.3   Packaging

19.2.4   More Sample Applications

19.3   Summary

20   Controlling Microcontrollers with JavaScript

20.1   Espruino

20.1.1   Technical Information

20.1.2   Connection and Installation

20.1.3   First Example

20.1.4   Controlling LEDs

20.1.5   More Modules

20.1.6   Reading Sensors

20.2   Tessel

20.2.1   Technical Information

20.2.2   Connection and Installation

20.2.3   Controlling LEDs

20.2.4   Programming the Push Buttons

20.2.5   Extending the Tessel with Modules

20.3   BeagleBone Black

20.3.1   Technical Information

20.3.2   Connection and Installation

20.3.3   Controlling LEDs

20.4   Arduino

20.4.1   The Firmata Protocol

20.4.2   Connection and Installation

20.4.3   The Johnny Five Node.js Module

20.5   Cylon.js

20.5.1   Controlling the BeagleBone Black with Cylon.js

20.5.2   Controlling the Tessel Board with Cylon.js

20.5.3   Controlling an Arduino with Cylon.js

20.6   Summary

21   Establishing a Professional Development Process

21.1   Automating Tasks

21.1.1   Automating Tasks with Grunt

21.1.2   Automating Tasks with Gulp

21.2   Automated Testing of Source Code

21.2.1   The Principle of Automated Tests

21.2.2   The Principle of Test-Driven Development

21.2.3   Automated Testing of Source Code with QUnit

21.2.4   Automated Testing of Source Code with mocha

21.3   Source Code Version Management

21.3.1   Introduction to Version Management

21.3.2   Installing and Configuring the Git Version Control System

21.3.3   Creating a New Local Repository

21.3.4   Cloning an Existing Repository

21.3.5   Transferring Changes to the Staging Area

21.3.6   Transferring Changes to the Local Repository

21.3.7   The Different States in Git

21.3.8   Transfering Changes to the Remote Repository

21.3.9   Transferring Changes from the Remote Repository

21.3.10   Working in a New Branch

21.3.11   Adopting Changes from a Branch

21.3.12   Overview of the Most Important Commands and Terms

21.4   Summary

A   The Author

Index

Service Pages

Legal Notes

Book Resources

The code listings presented in this book are available for you to download from the website for this book.

Go to https://www.rheinwerk-computing.com/5554. Scroll down to the Product Supplements section and click the Supplements List button. You will see the downloadable files, along with a brief description of the file content. Click the Download button to start the download. Depending on the size of the file (and your internet connection), it may take some time for the download to complete.

Preface

JavaScript, the lingua franca of the web, has become increasingly popular in recent years and is now used in many different areas. Be it web, mobile or server application development: JavaScript does a good job in all areas.

This book provides comprehensive insight into this important language that has become indispensable to web developers. Don't worry if you've never programmed before—you will also get an introduction to the basics of programming.

Although JavaScript appears to be quite simple at first glance and has long been considered a simple scripting language, this is not quite true. The specification behind JavaScript, called the ECMAScript standard, comprises more than a thousand pages. The specifications of the various application programming interfaces (APIs) that we discuss in this book are even more extensive in total. You can also write entire books on the JavaScript jQuery library and the Node.js platform. In a nutshell: it is not possible to discuss all these topics in detail in a single book, nor is this my goal.

The word comprehensive used in the title is not meant in the sense of all-encompassing, but in the sense of detailed, extensive, and versatile. I'll show you the basics of JavaScript; how to build web, server-side, and mobile applications using JavaScript; how to control microcontrollers using JavaScript; and a lot more. It is more important for me to demonstrate the most central and practical aspects, i.e. the aspects that you need in every-day JavaScript development, instead of discussing every last detail in an all-encompassing way.

Target Audience

This book is aimed at different audiences: on the one hand, readers who generally have no programming experience at all, neither in JavaScript nor in any other programming language. These readers can expect background knowledge of programming concepts and paradigms in this book, in addition to an introduction to JavaScript. Regardless of individual background knowledge, the book provides a comprehensive introduction to the language itself and to the most important APIs and application areas. On the other hand, the book is also aimed at readers who are already familiar with JavaScript and now want to deepen their experience or simply have a reliable, comprehensive reference book at hand.

In any case, to understand the JavaScript manual, it is an advantage if you have some knowledge of HTML and at least some knowledge of CSS. After all, there is a good reason why these two languages plus JavaScript constitute the core of modern web development.

Structure of the Book

The book can be roughly divided into four parts: In the first four chapters, you will learn the basics of programming and the language core of JavaScript—that is, the essential components of the language. Chapter 5 through Chapter 12 then focus on the application of JavaScript in web development: how to create dynamic content, how to retrieve content from the server using JavaScript, how to create graphics dynamically using JavaScript, and much more. Chapter 13 to Chapter 21 then deal with more advanced concepts, such as object-oriented and functional programming, the Node.js platform, mobile and desktop application development, and the use of JavaScript with the Internet of Things (IoT).

How Should I Read This Book?

The answer to this question depends on your level of knowledge, of both programming in general and the JavaScript language in particular. If you would describe yourself as a beginner, it is certainly best to work through the book from cover to cover, especially the first two parts—that is, Chapter 1 to Chapter 12. This will ensure that you do not omit any essential aspects that are necessary for understanding the following chapters.

Advanced readers can also skip individual chapters depending on their level of knowledge. In the code examples, we have deliberately taken care to keep them self-contained and not to stretch them over several chapters. This allows you to select individual topics without having to go through several chapters at once. In any case, you can also use the book as a reference: thanks to the comprehensive reference section, the (hopefully) meaningful headings, and the extensive index, the relevant information can be found quickly.

Acknowledgments

Writing a book always involves a lot of time, time that has to be freed up elsewhere. Most of all, therefore, I thank my wife and children for giving me the time I needed to do this.

For this English edition I would like to thank the linguists at Lemoine International GmbH for the translation, Melinda Rankin for copyediting, the team at Rheinwerk Publishing, especially Hareem Shafi, Kelly O’Callaghan, Graham Geary, and Hannah Lane, and the team at Rheinwerk Verlag who published the original German book: my editors Patricia Schiewald and Stephan Mattescheck for their constructive suggestions and support, as well as Sibylle Feldmann and the entire team at Rheinwerk Verlag. I would also like to thank Sebastian Springer for his many helpful comments and, as always, extraordinarily thorough expert opinion. Thank you all very much for your support!

I would also like to thank the publisher Hans Heise, with whose kind permission I was allowed to reuse excerpts from articles I wrote for iX and for heise Developer in this book. In this regard, I would especially like to thank Julia Schmidt.

I would also like to thank Max Bold from Ebner Media Group GmbH & Co. KG, with whose kind permission I was allowed to use excerpts from articles I wrote for the trade magazine web & mobile DEVELOPER.

Last but not least, of course, I thank you for purchasing this book and for the time you spend reading and working through it, and I hope you enjoy it. I appreciate receiving feedback on the book at [email protected]. If you're active on Twitter, I'd love for you to follow my account @cleancoderocker (https://twitter.com/cleancoderocker).

Philip AckermannRheinbach, Germany

1    Basics and Introduction

Before we get into creating JavaScript programs, this chapter will give you an overview of what’s meant by programming in the first place, what types of programming languages there are, and the historical background of the JavaScript language: How has this language evolved over the years? What is the relationship between JavaScript and ECMAScript? In addition, we’ll introduce the various application areas of JavaScript and explain how these have also changed in recent years.

This book is designed to not only teach you the JavaScript language but also introduce you to basic programming concepts in case you aren’t yet familiar with any programming language. In this introductory chapter, we’ll therefore first explain a few basic terms and concepts that will be helpful throughout the book. If you already have some experience in programming, you can skip at least the first part of this chapter. On the other hand, we have deliberately kept this part short because we don't want to bore you with theoretical treatises on programming but get you quickly started with JavaScript. Therefore, you might also consider this part a quick review.

One more quick note about the book before we get right into it: Occasionally, when discussing certain topics, we’ll touch on concepts that will be explained fully later. In general, this can’t always be avoided in a book on programming languages. In a way, as an author, you are faced with the chicken-and-egg problem: one cannot be explained without the other and vice versa. In such cases, for the sake of clarity, we have included references to the chapters or sections in which the respective concepts are discussed more fully.

1.1    Programming Basics

Before you can get started with actual programming, you need some basic understanding of what programming is all about. Why do we write programs? How do programs work? What role does JavaScript play in this context? And how does this language differ from other programming languages?

1.1.1    Communicating with the Computer

Let's start with the question of why we want to write programs in the first place, or rather, what goal we pursue by doing it. Primarily, programming is about letting a computer take over certain tasks. These can be, for example, complex problems that we humans would struggle to figure out ourselves or things that help us work more effectively in everyday life. For example, think of word processors, email programs, or your browser. All these tools have been programmed by someone.

Simply put, the task of a developer is to give instructions to the computer so that it is able to perform the tasks assigned to it. In other words, as a developer, you formulate individual steps for solving a specific problem, such as sorting data in a table or validating form data entered on a web page. The steps are then evaluated one by one by the computer. This is roughly comparable to a cooking recipe. There, too, individual steps are defined that you need to follow in order to reach your goal. In programming, the developer is the one who provides the computer with a recipe to follow.

In summary, the steps for solving a problem (i.e., the recipe) in computer science and software development are generally referred to as algorithms. Therefore, a program (also called software or an application) is a sequence of algorithms and, as such, a sequence of instructions that can be executed by the computer.

Definition

In software development, the steps defined for solving a problem are collectively called an algorithm. This is comparable to cooking recipes, operating instructions, or manuals. In this sense, an algorithm is a set of instructions for the computer for how to solve a particular problem.

Definition

A program or piece of software is composed of numerous different algorithms.

At the beginning, programming novices often find it difficult to think like a computer and to define the steps within an algorithm accordingly. After all, computers follow the instructions you give them in a very precise way. While you as a human being can always use your mind when going through a cooking recipe and vary certain steps according to your experience, a computer assumes that the steps you formulated should be carried out exactly as set out. Conversely, this also means that you as a developer must formulate the instructions just as precisely and put yourself in the position of the computer.

Tip

When I started programming in 2000, I kept wondering how anyone could ever learn how to write programs and admired experienced developers for their knowledge. After all these years, I can tell you: you only learn it by doing it yourself. Therefore, you should not only read this book, but really work through it and create programs yourself again and again. However, don't put too much pressure on yourself, and don't stress yourself out if something doesn't work right away. After all, as a developer, you need one thing more than anything: perseverance, and the willingness to learn something new every day.

1.1.2    Programming Languages

Deep down, computers work with zeros and ones; that much is common knowledge. A more professional term for "zeros and ones" is binary code or machine code or machine language. The background for this binary code is the technical level that only knows two states: zero for "power off" and one for "power on".

Simply put, various combinations of zeros and ones ultimately make the computer's hardware do various things, such as display a pixel on your monitor in this or that color, respond to mouse movements or keyboard input, or send an email over the network.

But because it would be incredibly complicated (and disproportionately time-consuming) for developers like us to phrase the instructions for the computer in zeros and ones, clever people at some point invented programming languages that abstract and simplify this interaction with the computer.

Programming languages can be further classified into different categories depending on their degree of abstraction. JavaScript is one of the so-called high-level programming languages, so it abstracts relatively far from the zeros and ones. Assembly languages, on the other hand, are much less abstract. They don’t require you to work with zeros and ones either, but the commands used are nevertheless relatively cryptic, and programming is comparatively complex (see Figure 1.1). The commands you use in JavaScript, on the other hand, are quite catchy, understandable, and easy to remember after you get used to them, as you'll soon see.

Note

JavaScript is a high-level programming language.

Figure 1.1High-Level Programming Languages Abstract from Machine Code

As a developer, you store everything you program via a programming language in ordinary text files called source files. The content of such a file is called source text or source code.

Definition

The source code is what you as a developer write in a given programming language. Machine code, on the other hand, refers to the code that is read and executed by the computer.

For the computer to understand and implement the instructions written in the source code, the source code must be translated to a format that the computer can understand—that is, to the previously mentioned machine code made of zeros and ones (see Figure 1.2).

Figure 1.2     Source Code Understandable to Developers Must Be Converted into Machine Code That Is Understandable to Computers so That They Can Act on It

Basically, there are two different ways to achieve this: via compilers or via interpreters. (Explanations of both will follow shortly.) Depending on whether a programming language uses a compiler or an interpreter, it is a compiled programming language, an interpreted programming language or a so-called intermediate language.

Before we explain the exact differences among these three language types and clarify what a compiler or an interpreter is, let’s note one point: JavaScript is an interpreted programming language. This has advantages, but also disadvantages, as we will see in a moment.

Compiled Programming Languages

In the case of compiled programming languages, a compiler converts the source code into machine code or into an executable machine code file (see Figure 1.3). This happens by translating the instructions written in the source code into a sequence of instructions for the computer. Programs generated by a compiler in this way can then be executed directly on the operating system for which they have been compiled, without the need for any other auxiliary components.

Figure 1.3     A Compiler Converts the Source Code into Executable Machine Code

Examples of compiled programming languages include C and C++. For example, in order to run a program written in C++, it must first be converted using an appropriate C++ compiler. But because the latter differs between operating systems, a separate version must be compiled for every operating system (see Figure 1.4).

Figure 1.4     C++, for Example, Is a Compiled Programming Language

To this end, you need a separate compiler for every operating system. To run the program on Windows, it must first be compiled on Windows using an appropriate compiler. To run it on Linux, it must be compiled with a compiler on Linux, and the same applies to macOS if the program is to be run on a Mac. Although there are approaches to compile code on one operating system to run on another operating system (e.g., on Linux to run on Windows or vice versa; this technique is called cross-compilation), this does not change the fact that you have to spend quite a lot of effort to get a C++ program up and running on different operating systems. And we haven’t even considered the processor architectures (32 bit and 64 bit), each of which requires a different compilation method.

Despite all the effort required, compiled programs still have a crucial advantage that we mentioned in passing: the machine code generated in each case can be executed on the respective operating system without auxiliary tools. Thus, no other programs need to be installed on the operating system to run a program compiled into machine code. This is a significant difference from interpreted programs, which we will discuss next.

Definition

Programs compiled for a specific operating system are also called native programs or native applications.

Interpreted Programming Languages

With interpreted programming languages, it isn’t necessary to compile the source code. The source code is not translated by a compiler but evaluated by an interpreter (see Figure 1.5). Such an interpreter must be installed on the computer (or on the corresponding operating system) on which the program is to be executed (in contrast to the compiler, which only needs to be installed on the computer on which the corresponding source code is compiled).

Figure 1.5     An Interpreter Evaluates the Source Code Directly and Converts It Instruction by Instruction into Machine Code

JavaScript is therefore, as already revealed, an interpreted programming language (see Figure 1.6). This means that you can basically use any text editor to write a JavaScript program and execute the source code directly in a browser without any additional intermediate steps.

Figure 1.6JavaScript Is an Interpreted Programming Language That Is Evaluated by a JavaScript Interpreter

Note

In the developer community, interpreted languages are usually very popular because they allow relatively fast development, precisely because the additional compilation step is omitted.

Interpreted programming languages thus require an interpreter to execute a program. Often this is a component of a so-called runtime environment (RTE). RTEs are used to enable application programs to run on a given operating system. In addition to an interpreter, RTEs also provide basic functions such as reading and writing files and access to peripheral devices (mouse, keyboard, printer, etc.).

In most cases and at the beginning, you will probably use one of the many browsers that already include a JavaScript RTE because they can natively interpret JavaScript. But there are also RTEs available that enable you to run JavaScript applications outside the browser.

Check Support for Individual Language Features

The individual RTEs differ to some extent with regard to the supported JavaScript language features. You can find a good overview on the website www.caniuse.com.

One RTE that has become very popular in recent years is Node.js. We’ve even dedicated an entire chapter to this topic (Chapter 17). Other JavaScript interpreters, which are very lightweight in terms of size (and therefore require little disk space), are also suitable for running JavaScript on microcontrollers. Chapter 20 deals with this topic.

In addition to RTEs for JavaScript, there are also RTEs for other programming languages. Well-known examples include Java Runtime Environment (JRE) for running Java programs or Microsoft's .NET Common Language Runtime (CLR), which can run programs written in C#, Visual Basic, or C++.

Figure 1.7 again shows an overview of the principle of RTEs and their relation to native applications.

Figure 1.7     The Principle of Runtime Environments

Note

JavaScript is not a compiled language, but an interpreted language.

Both the compiler and the interpreter approach have advantages, but also disadvantages. Table 1.1 shows a brief summary.

Compiler

Interpreter

The program must be recompiled for execution every time.

The program can be executed directly.

Usually delivers very good performance because the source code doesn’t have to be converted at runtime.

Tends to be less efficient than compiled programs as source code conversion occurs at program runtime. Nowadays, so-called just-in-time (JIT) compilers are often used in this context. They convert the source code or frequently executed source code into machine code that can then be executed relatively quickly.

Due to the additional compilation step, syntax errors are detected faster.

Because syntax errors are only detected at runtime, they can easily be overlooked.

Table 1.1     Advantages and Disadvantages of Compilers and Interpreters

Intermediate Languages

There are some programming languages that cannot be clearly assigned to one of the two categories mentioned (compiled and interpreted) as they use both compilers and interpreters. In Java, for example, the source code is compiled by a compiler into so-called bytecode, a kind of intermediate code, which in turn requires an interpreter in order to be executed (see Figure 1.8).

Figure 1.8     There Are Also Programming Languages That Use a Combination of Compiler and Interpreter

The advantage of this approach is that Java applications do not have to be compiled on the same operating system on which they will later be executed (in contrast to compiled languages) as the bytecode is independent of the operating system. The only thing that needs to be present on the respective target operating system is an interpreter for the bytecode—in other words, a runtime environment for Java (see Figure 1.9).

Figure 1.9     The Java Programming Language Is an Example of a Language That Uses Compilers and Interpreters

Overview of Different Programming Languages

You now know the difference between compiled and interpreted programming languages, and you also know that there are intermediate languages that use a combination of both approaches. You also learned about one example in each of these language categories: C or C++ as an example of compiled programming languages, Java as an example of an intermediate language, and finally JavaScript as an example of an interpreted language. But what about other well-known programming languages? You can find a selection of these in Table 1.2.

Programming Language

Type

Ada

Compiled

BASIC

Interpreted

C

Compiled

C++

Compiled

C#

Compiled

COBOL

Compiled

Fortran

Compiled

Go

Compiled

Java

Intermediate language

JavaScript

Interpreted

Lisp

Intermediate language

Objective-C

Compiled

Perl

Interpreted

PHP

Interpreted

Python

Interpreted

Ruby

Interpreted

Rust

Compiled

Swift

Compiled

Visual Basic

Compiled

Table 1.2     Categorization of Different Programming Languages

1.1.3    Tools for Program Design

As a developer, you’re often itching to start with the implementation of an algorithm—but you should avoid being too hasty in the process. It’s better to think about the structure of the algorithm first: Which individual steps are necessary to solve the given problem? What are the special cases to consider? What input data does the algorithm require? What is the result that should be returned?

It’s best to initially follow these steps when implementing an algorithm:

Set the goal of the algorithmWhat do you want to achieve with the algorithm? What problem do you want the computer to solve for you? Is there something be calculated? Is there data to be sorted or user input to be checked?

Define the stepsBreak down the problem into individual steps. In what order do these steps have to be performed? How are the steps related? Do individual steps need to be performed repeatedly? Or under certain conditions only? Soon, we’ll introduce flowchart notation and the so-called pseudocode technique, which can help you plan the flow of an algorithm.

Write the algorithmFor the computer to understand your algorithm, you need to write it in a programming language. In this case, that's JavaScript. The following nearly 1,300 pages will help you with this.

Definition

In the context of programming and software development, implementation means the realization of an algorithm (or more generally, a program flow) in a specific programming language.

Note

The more complex the problem, the more important it is that you think about the individual steps before implementation.

Flowcharts

Flowcharts, also called program flowcharts, are graphical representations for describing algorithms that allow you to precisely define individual steps and the overall flow. The more experienced you are as a developer and the less complex a problem is, the more likely you are to avoid drawing flowcharts beforehand. In other cases, however, flowcharts can be enormously helpful in getting a clear idea of what an algorithm is supposed to do. Trust me: even if this seems redundant at first (after all, you still need to write the appropriate source code after drawing the flowchart), proper planning pays off later. The truth is that the more complex an algorithm or the preceding problem is, the more worthwhile is the preliminary work.

Flowcharts essentially consist of boxes in different shapes connected by lines. Figure 1.10 shows an example of a flowchart. It illustrates the flow of a program for the login process on a website. If a valid combination of username and password is entered, the user profile is to be loaded and redirected to the welcome page. If the input is incorrect, and if the maximum number of failed login attempts has not yet been exceeded, an error message is to be displayed and the user should be redirected back to the login page. If, on the other hand, the maximum number of failed login attempts has been exceeded, then the user should be blocked and a notification email should be sent to the responsible administrator.

Figure 1.10     Flowchart Example

The elements in the flowchart are described ahead. Table 1.3 also gives an overview of these elements.

Start/stop control points are used to describe the beginning and the end of an algorithm. They are represented in flowcharts as rounded rectangles. They usually contain labels such as "Start," "Begin," "Stop," or "End" or more detailed wording that also includes the name of the algorithm, such as in the example "Start login," "Login failed," or "Login completed successfully."

Individual statements or operations of an algorithm are represented in a flowchart by normal rectangles. As a label, they contain a short, meaningful description of what is to be done in each step—for example, "Create user session."

The input and output of the program are represented by parallelograms. They are also labeled with a short description of what kind of input is expected by the program (e.g., "Input username and password") or what kind of output will be generated (e.g., "Show error message" or "Show welcome page").

If a decision has to be made at a certain point within an algorithm about which of the following instructions is to be executed, this is described in flowcharts using decision points, graphically represented as square diamonds with two paths leading away from each. As a rule, they are labeled with questions that can be answered with yes or no or with questions that can be answered with one of two possible answers. This is because a decision point is used to follow one path or the other in the flowchart, depending on the particular answer. The answers are written on the corresponding lines leading from the decision point. One of the decision points in the example is used to check whether the credentials entered are valid. If this is true (i.e., if the question "Access data valid?" is answered with "Yes"), the path shown on the right-hand side of the chart is the one to be followed. If not, the path shown on the left-hand side is to be followed.

Rectangles with two lines on the left and right sides are used to define calls to subroutines (or subalgorithms), which again consist of various steps. In the example flowchart, they describe the subroutines of locking the user and sending the notification email to the administrator.

Element

Label

Description

Start/stop checkpoint

Used to describe the beginning and the end of an algorithm

Operation

Used to describe individual statements or operations of an algorithm

Input and output

Used to describe input or output

Decision point

Used to describe branches in the algorithm

Execute a subroutine

Used to describe calls to subroutines

Connection

Used to connect individual elements in the flowchart and thus describe the flow of the algorithm

Table 1.3     The Most Important Elements of Flowcharts

Other Elements in Flowcharts

There are a few more elements that you can use in flowcharts, but they are not as commonly used and we don't need them for the remaining examples in the book. You can find an overview of these at https://en.wikipedia.org/wiki/Flowchart, for example.

Flowcharts Are Independent of the Programming Language

Another advantage of flowcharts is that they are independent of the programming language used. In our case, it doesn't really matter (after all, we want to program in JavaScript)—but in principle, this can be considered an advantage.

Pseudocode

As an alternative (or supplement) to flowcharts, you can also create so-called pseudocode for program design. This means that you write the individual steps of an algorithm in more or less natural language instead of in a concrete programming language. Listing 1.1 shows the algorithm from Figure 1.10, transferred to pseudocode.

program start login read username and password if user data valid then create user session show welcome page else if maximum number of login attempts reached then call subroutine to lock user call subroutine to send email to administrator display error message exit program else display error message redirect to input go to user data inputprogram end login

Listing 1.1     Pseudocode Example

Unlike flowcharts, where the elements used are predetermined, pseudocode has no restrictions in this regard. As a rule, you use words and sentence components such as "read", "if ... then ... else", "show", "output", "as long as ... execute", and the like. Approximate translations of elements from flowcharts to pseudocode are given in Table 1.4.

An essential feature of pseudocode (which also shows the similarity to real source code) are the indentations at the beginning of lines. As you can see in Listing 1.1, program lines that are executed depending on the respective preceding program line are indented further to the right (typically by two to four spaces).

Pseudocode

Element from Flowchart

program startprogram end

Start/stop checkpoint

Active sentences, starting with verbs like create, show, etc.

Operation

read, output

Input and output

if ... else

Decision point

as long as ... execute

Repetitions

subroutine call

Execute a subroutine

Table 1.4     Relationship between Sentence Components in Pseudocode and Elements in Flowcharts

The advantage of pseudocode, as with flowcharts, is that you can think about the flow of an algorithm in advance without having to start directly with the implementation in your chosen programming language. Although you already write text that is quite similar to the later source code, you do not have to deal with the syntactical peculiarities of the respective programming language. This allows you to focus entirely on the algorithm flow. In addition, especially for more complex algorithms, pseudocode is much more compact than flowcharts.

Flowcharts, Pseudocode, and Programming Languages

In the course of the book, you will notice that there are certain language constructs in programming languages (here, in JavaScript in particular) to which both flowcharts and pseudocode can be applied with relative ease.

1.2    Introduction to JavaScript

Now that we’ve looked at programming languages in general, this section will give a brief overview of JavaScript, but without going into the details of the language. Essentially, it will offer a brief historical overview of the language and introduce various application areas where JavaScript is used nowadays.

1.2.1    History

Histories of programming languages often are rather bland and rarely very interesting. For this reason, we’ll keep this section as short as possible and give only the most important points without going into version details and the like.

Like software programs, programming languages are also updated from time to time. In that case, new features are added to the programming language to make the developer's work easier, while other features that caused problems in the past or were simply rarely used are dropped. So there were different versions of JavaScript in the past as well.

The history of JavaScript begins in 1995, when Brendan Eich designed the language for Netscape Navigator (a now outdated browser) in a record time of two weeks. In the beginning, JavaScript did not have its current name; it was initially called Mocha and LiveScript. Due to a cooperation between Netscape and Sun (the company behind the Java programming language) and for marketing reasons (the Java programming language was already quite popular at the time) the language was finally renamed to JavaScript. However, the similarity of the name to Java should not lead you to jump to conclusions: apart from the similar name, the two languages have little in common.

Shortly after the release of JavaScript, Microsoft followed up with a more or less compatible language (JScript) for Internet Explorer 3.0. To reconcile these two similar languages, Netscape then submitted JavaScript to the European Computer Manufacturers Association (ECMA), with the goal of creating a unified standard for the language. This standard has since been running under the name ECMAScript, which was adopted in version 6 in 2015 (ES6 or ES2015 for short). Since then, new features have been added to the standard every year, so it was agreed not to use a separate consecutive version number, but to simply list the respective calendar year in the version number (see Table 1.5).

Version Name

Year of Publication

ES1

1997

ES2

1998

ES3

1999

ES4

Not released

ES5

2009

ES6/ES2015

2015

ES2016

2016

ES2017

2017

ES2018

2018

ES2019

2019

ES2020

2020

ES2021

2021

Table 1.5     JavaScript/ECMAScript Version History

Other Variants of ECMAScript

Thus, JavaScript is only one variant of this standard (examples of other variants are the ActionScript known from Flash and the ExtendScript used in numerous Adobe products).

1.2.2    Fields of Application

Nowadays, JavaScript not only plays a leading role in the development of web pages and web applications but also is a good choice for various other types of applications. The most important application areas are detailed ahead.

Definition of Terms

Since we use the terms web page, website, and web application repeatedly throughout the book, we will briefly explain them here. A web page is a single HTML document that can be accessed at a specific URL (e.g., www.rheinwerk-computing.com/javascript_5554). A website is a collection of various individual web pages (e.g., www.rheinwerk-computing.com).

A web application, however, is a web page that feels more like a desktop application than a web page. Examples include Google Documents and similar web-based software applications. Another term for such web applications is rich internet applications, which refers to web applications with rich content and features.

Frontend of Web Applications

When developing websites and web applications, a distinction is generally made between the part that takes place on the client side in the browser (the so-called frontend) and the part that takes place on the server side (the so-called backend). JavaScript has its roots in frontend development, and for a long time it was mainly used to "spruce up" the interface of a web page with dynamic effects.

Figure 1.11     Relationship between Frontend and Backend (or Client Side and Server Side)

A related term coined back in the 1990s is Dynamic HTML (DHTML), which is the dynamic modification of HTML code using JavaScript. DHTML has been forgotten these days because, from today's point of view, it was based on rather ugly JavaScript code and was characterized more by bad practices than by best practices. Therefore, in Chapter 5 we will not deal with DHTML at all but with DOM scripting, which is another way of dynamically modifying the HTML of a web page.

Definition

DOM stands for Document Object Model and refers to the object model behind web pages. This topic will be discussed in detail in Chapter 5. There we will also explain what an object model is in the first place.

Definition

In the context of software development, bad practices refers to poor programming techniques, while best practices refers to particularly good programming techniques.

On various websites, you have probably seen functionality for sorting tables (see Figure 1.12) and filtering table entries according to certain criteria (see Figure 1.13). Both are typical use cases of dynamically modifying a web page and thus of using JavaScript.

An important milestone for JavaScript and the basis for more complex web applications was the introduction of the XMLHttpRequest object and the associated Ajax (Asynchronous JavaScript and XML), respectively, which allowed asynchronous requests to be sent from the browser to a server for the first time. Why this is so special, in which cases it can be useful, and what this XMLHttpRequest object is in the first place is explained in detail in Chapter 9. For now, note that it usually improves the usability of a web application, helps to avoid loading times, and makes a web application appear much more dynamic.

Figure 1.12     Sorting Data Using JavaScript

Figure 1.13     Filtering Data with JavaScript