29,99 €
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:
Seitenzahl: 1276
Veröffentlichungsjahr: 2024
Philip Ackermann
The Comprehensive Guide
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
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
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:
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.
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.
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.
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.
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).
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.
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
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.
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?
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.
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.
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.
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.
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.
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.
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.
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.
Programs compiled for a specific operating system are also called native programs or native applications.
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
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.
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
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
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
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
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.
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.
The more complex the problem, the more important it is that you think about the individual steps before implementation.
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
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.
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.
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.
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.
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.
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.
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
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).
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.
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.
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.
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.
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