Node.Js 562 Background

Total Page:16

File Type:pdf, Size:1020Kb

Node.Js 562 Background Eloquent JavaScript 3rd edition Marijn Haverbeke Copyright © 2018 by Marijn Haverbeke This work is licensed under a Creative Commons attribution-noncommercial license (http://creativecommons.org/licenses/by-nc/3.0/). All code in the book may also be considered licensed under an MIT license (https: //eloquentjavascript.net/code/LICENSE). The illustrations are contributed by various artists: Cover and chap- ter illustrations by Madalina Tantareanu. Pixel art in Chapters 7 and 16 by Antonio Perdomo Pastor. Regular expression diagrams in Chap- ter 9 generated with regexper.com by Jeff Avallone. Village photograph in Chapter 11 by Fabrice Creuzot. Game concept for Chapter 16 by Thomas Palef. The third edition of Eloquent JavaScript was made possible by 325 financial backers. You can buy a print version of this book, with an extra bonus chapter in- cluded, printed by No Starch Press at http://a-fwd.com/com=marijhaver- 20&asin-com=1593279507. i Contents Introduction 1 On programming .......................... 2 Why language matters ....................... 4 What is JavaScript? ......................... 9 Code, and what to do with it ................... 11 Overview of this book ........................ 12 Typographic conventions ...................... 13 1 Values, Types, and Operators 15 Values ................................. 16 Numbers ............................... 17 Strings ................................ 21 Unary operators ........................... 24 Boolean values ............................ 25 Empty values ............................. 29 Automatic type conversion ..................... 29 Summary ............................... 33 ii 2 Program Structure 34 Expressions and statements .................... 34 Bindings ............................... 36 Binding names ............................ 39 The environment .......................... 40 Functions ............................... 40 The console.log function ...................... 41 Return values ............................ 42 Control flow ............................. 43 Conditional execution ........................ 44 while and do loops .......................... 47 Indenting Code ........................... 50 for loops ............................... 51 Breaking Out of a Loop ...................... 52 Updating bindings succinctly ................... 53 Dispatching on a value with switch ................ 54 Capitalization ............................ 56 Comments .............................. 57 Summary ............................... 58 Exercises ............................... 59 3 Functions 62 Defining a function ......................... 63 Bindings and scopes ......................... 65 Functions as values ......................... 68 Declaration notation ........................ 68 Arrow functions ........................... 70 iii The call stack ............................ 71 Optional Arguments ......................... 73 Closure ................................ 76 Recursion ............................... 78 Growing functions .......................... 83 Functions and side effects ..................... 87 Summary ............................... 88 Exercises ............................... 89 4 Data Structures: Objects and Arrays 91 The weresquirrel ........................... 92 Data sets ............................... 93 Properties .............................. 94 Methods ............................... 95 Objects ................................ 97 Mutability .............................. 101 The lycanthrope’s log ........................ 103 Computing correlation ....................... 106 Array loops .............................. 109 The final analysis .......................... 110 Further arrayology .......................... 113 Strings and their properties .................... 116 Rest parameters ........................... 119 The Math object ........................... 120 Destructuring ............................ 123 JSON ................................. 124 Summary ............................... 126 iv Exercises ............................... 127 5 Higher-Order Functions 131 Abstraction .............................. 132 Abstracting repetition ....................... 134 Higher-order functions ....................... 136 Script data set ............................ 138 Filtering arrays ........................... 139 Transforming with map ....................... 141 Summarizing with reduce ...................... 142 Composability ............................ 144 Strings and character codes .................... 146 Recognizing text ........................... 149 Summary ............................... 152 Exercises ............................... 152 6 The Secret Life of Objects 155 Encapsulation ............................ 155 Methods ............................... 156 Prototypes .............................. 159 Classes ................................ 161 Class notation ............................ 164 Overriding derived properties ................... 165 Maps ................................. 167 Polymorphism ............................ 170 Symbols ................................ 171 The iterator interface ........................ 173 v Getters, setters, and statics .................... 177 Inheritance .............................. 180 The instanceof operator ....................... 182 Summary ............................... 183 Exercises ............................... 184 7 Project: A Robot 187 Meadowfield ............................. 187 The task ............................... 190 Persistent data ............................ 193 Simulation .............................. 194 The mail truck’s route ....................... 197 Pathfinding .............................. 198 Exercises ............................... 202 8 Bugs and Errors 204 Language ............................... 204 Strict mode .............................. 205 Types ................................. 207 Testing ................................ 209 Debugging .............................. 211 Error propagation .......................... 213 Exceptions .............................. 215 Cleaning up after exceptions .................... 218 Selective catching .......................... 221 Assertions .............................. 224 Summary ............................... 225 vi Exercises ............................... 226 9 Regular Expressions 228 Creating a regular expression ................... 229 Testing for matches ......................... 230 Sets of characters .......................... 230 Repeating parts of a pattern .................... 233 Grouping subexpressions ...................... 234 Matches and groups ......................... 235 The Date class ............................ 237 Word and string boundaries .................... 239 Choice patterns ........................... 240 The mechanics of matching .................... 241 Backtracking ............................. 243 The replace method ......................... 246 Greed ................................. 249 Dynamically creating RegExp objects .............. 251 The search method ......................... 252 The lastIndex property ....................... 253 Parsing an INI file .......................... 256 International characters ....................... 260 Summary ............................... 262 Exercises ............................... 264 10 Modules 267 Modules ................................ 268 Packages ............................... 269 vii Improvised modules ......................... 271 Evaluating data as code ...................... 272 CommonJS .............................. 273 ECMAScript modules ........................ 277 Building and bundling ....................... 280 Module design ............................ 281 Summary ............................... 284 Exercises ............................... 285 11 Asynchronous Programming 287 Asynchronicity ............................ 288 Crow tech ............................... 290 Callbacks ............................... 291 Promises ............................... 295 Failure ................................ 297 Networks are hard .......................... 300 Collections of promises ....................... 303 Network flooding .......................... 305 Message routing ........................... 306 Async functions ........................... 310 Generators .............................. 314 The event loop ............................ 316 Asynchronous bugs ......................... 318 Summary ............................... 320 Exercises ............................... 321 viii 12 Project: A Programming Language 323 Parsing ................................ 323 The evaluator ............................ 330 Special forms ............................. 333 The environment .......................... 335 Functions ............................... 338 Compilation ............................. 340 Cheating ............................... 341 Exercises ............................... 343 13 JavaScript and the Browser 346 Networks and the Internet ..................... 347 The Web ............................... 349 HTML ................................ 350 HTML and JavaScript ....................... 354 In the sandbox ............................ 356 Compatibility and the browser wars ............... 357 14 The Document Object Model 359 Document structure ......................... 359 Trees ................................. 362 The standard ............................. 363 Moving through the tree
Recommended publications
  • Lightweight Django USING REST, WEBSOCKETS & BACKBONE
    Lightweight Django USING REST, WEBSOCKETS & BACKBONE Julia Elman & Mark Lavin Lightweight Django LightweightDjango How can you take advantage of the Django framework to integrate complex “A great resource for client-side interactions and real-time features into your web applications? going beyond traditional Through a series of rapid application development projects, this hands-on book shows experienced Django developers how to include REST APIs, apps and learning how WebSockets, and client-side MVC frameworks such as Backbone.js into Django can power the new or existing projects. backend of single-page Learn how to make the most of Django’s decoupled design by choosing web applications.” the components you need to build the lightweight applications you want. —Aymeric Augustin Once you finish this book, you’ll know how to build single-page applications Django core developer, CTO, oscaro.com that respond to interactions in real time. If you’re familiar with Python and JavaScript, you’re good to go. “Such a good idea—I think this will lower the barrier ■ Learn a lightweight approach for starting a new Django project of entry for developers ■ Break reusable applications into smaller services that even more… the more communicate with one another I read, the more excited ■ Create a static, rapid prototyping site as a scaffold for websites and applications I am!” —Barbara Shaurette ■ Build a REST API with django-rest-framework Python Developer, Cox Media Group ■ Learn how to use Django with the Backbone.js MVC framework ■ Create a single-page web application on top of your REST API Lightweight ■ Integrate real-time features with WebSockets and the Tornado networking library ■ Use the book’s code-driven examples in your own projects Julia Elman, a frontend developer and tech education advocate, started learning Django in 2008 while working at World Online.
    [Show full text]
  • Basic Structures: Sets, Functions, Sequences, and Sums 2-2
    CHAPTER Basic Structures: Sets, Functions, 2 Sequences, and Sums 2.1 Sets uch of discrete mathematics is devoted to the study of discrete structures, used to represent discrete objects. Many important discrete structures are built using sets, which 2.2 Set Operations M are collections of objects. Among the discrete structures built from sets are combinations, 2.3 Functions unordered collections of objects used extensively in counting; relations, sets of ordered pairs that represent relationships between objects; graphs, sets of vertices and edges that connect 2.4 Sequences and vertices; and finite state machines, used to model computing machines. These are some of the Summations topics we will study in later chapters. The concept of a function is extremely important in discrete mathematics. A function assigns to each element of a set exactly one element of a set. Functions play important roles throughout discrete mathematics. They are used to represent the computational complexity of algorithms, to study the size of sets, to count objects, and in a myriad of other ways. Useful structures such as sequences and strings are special types of functions. In this chapter, we will introduce the notion of a sequence, which represents ordered lists of elements. We will introduce some important types of sequences, and we will address the problem of identifying a pattern for the terms of a sequence from its first few terms. Using the notion of a sequence, we will define what it means for a set to be countable, namely, that we can list all the elements of the set in a sequence.
    [Show full text]
  • GNU Emacs Manual
    GNU Emacs Manual GNU Emacs Manual Sixteenth Edition, Updated for Emacs Version 22.1. Richard Stallman This is the Sixteenth edition of the GNU Emacs Manual, updated for Emacs version 22.1. Copyright c 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the Invariant Sections being \The GNU Manifesto," \Distribution" and \GNU GENERAL PUBLIC LICENSE," with the Front-Cover texts being \A GNU Manual," and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled \GNU Free Documentation License." (a) The FSF's Back-Cover Text is: \You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development." Published by the Free Software Foundation 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA ISBN 1-882114-86-8 Cover art by Etienne Suvasa. i Short Contents Preface ::::::::::::::::::::::::::::::::::::::::::::::::: 1 Distribution ::::::::::::::::::::::::::::::::::::::::::::: 2 Introduction ::::::::::::::::::::::::::::::::::::::::::::: 5 1 The Organization of the Screen :::::::::::::::::::::::::: 6 2 Characters, Keys and Commands ::::::::::::::::::::::: 11 3 Entering and Exiting Emacs ::::::::::::::::::::::::::: 15 4 Basic Editing
    [Show full text]
  • Analisi Del Progetto Mozilla
    Università degli studi di Padova Facoltà di Scienze Matematiche, Fisiche e Naturali Corso di Laurea in Informatica Relazione per il corso di Tecnologie Open Source Analisi del progetto Mozilla Autore: Marco Teoli A.A 2008/09 Consegnato: 30/06/2009 “ Open source does work, but it is most definitely not a panacea. If there's a cautionary tale here, it is that you can't take a dying project, sprinkle it with the magic pixie dust of "open source", and have everything magically work out. Software is hard. The issues aren't that simple. ” Jamie Zawinski Indice Introduzione................................................................................................................................3 Vision .........................................................................................................................................4 Mozilla Labs...........................................................................................................................5 Storia...........................................................................................................................................6 Mozilla Labs e i progetti di R&D...........................................................................................8 Mercato.......................................................................................................................................9 Tipologia di mercato e di utenti..............................................................................................9 Quote di mercato (Firefox).....................................................................................................9
    [Show full text]
  • Introduction
    Introduction A need shared by many applications is the ability to authenticate a user and then bind a set of permissions to the user which indicate what actions the user is permitted to perform (i.e. authorization). A LocalSystem may have implemented it's own authentication and authorization and now wishes to utilize a federated Identity Provider (IdP). Typically the IdP provides an assertion with information describing the authenticated user. The goal is to transform the IdP assertion into a LocalSystem token. In it's simplest terms this is a data transformation which might include: • renaming of data items • conversion to a different format • deletion of data • addition of data • reorganization of data There are many ways such a transformation could be implemented: 1. Custom site specific code 2. Scripts written in a scripting language 3. XSLT 4. Rule based transforms We also desire these goals for the transformation. 1. Site administrator configurable 2. Secure 3. Simple 4. Extensible 5. Efficient Implementation choice 1, custom written code fails goals 1, 3 and 4, an admin cannot adapt it, it's not simple, and it's likely to be difficult to extend. Implementation choice 2, script based transformations have a lot of appeal. Because one has at their disposal the full power of an actual programming language there are virtually no limitations. If it's a popular scripting language an administrator is likely to already know the language and might be able to program a new transformation or at a minimum tweak an existing script. Forking out to a script interpreter is inefficient, but it's now possible to embed script interpreters in the existing application.
    [Show full text]
  • Learning Javascript Design Patterns
    Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern
    [Show full text]
  • Web Age Webinar Series
    Welcome! Check that you can "raise your hand" next to your name on the left When we start I'll ask everyone to raise their hand to verify you can hear me To ask a question during the presentation type it in the “Questions” section and raise your hand to help me notice it ©WebAgeSolutions.com 1 CLASH OF THE JAVASCRIPT TITANS: BACKBONE.JS AND ANGULAR.JS A comparison and contrast between Backbone.js and Angular.js ©WebAgeSolutions.com 2 Introduction Eric W. Greene Web Application Developer [email protected] Web Age Solutions Web Age Solutions provides mentoring services and skills training to companies navigating the world of online business. ©WebAgeSolutions.com 3 Overview of Talk The Problem to be Solved Framework or Library? Differences and Benefits of Each The Big Issue: Two-Way Data Binding Browserify and Node.js Conclusion ©WebAgeSolutions.com 4 The Problem to be Solved What problem do JavaScript solutions like Backbone.js and Angular.js solve? Single Page Applications (SPAs) SPAs need the following • Structure to manage UI and application data • Method for accessing network resources such as REST services • Routing System for going from page to page without reloading the web page from the server • Template System for constructing views ©WebAgeSolutions.com 5 Framework or Library? What is the difference between a framework and library? Why is Backbone.js a library? Why is Angular.js a framework? Which are the benefits and costs of using frameworks and libraries? ©WebAgeSolutions.com 6 The Big Issue: Two-Way Data Binding Two-Way Data
    [Show full text]
  • 13 Templates-Generics.Pdf
    CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 – 5 Gilad Bracha, Generics in the Java Programming Language Questions • If subtyping and inheritance are so great, why do we need type parameterization in object- oriented languages? • The great polymorphism debate – Subtype polymorphism • Apply f(Object x) to any y : C <: Object – Parametric polymorphism • Apply generic <T> f(T x) to any y : C Do these serve similar or different purposes? Outline • C++ Templates – Polymorphism vs Overloading – C++ Template specialization – Example: Standard Template Library (STL) – C++ Template metaprogramming • Java Generics – Subtyping versus generics – Static type checking for generics – Implementation of Java generics Polymorphism vs Overloading • Parametric polymorphism – Single algorithm may be given many types – Type variable may be replaced by any type – f :: tt => f :: IntInt, f :: BoolBool, ... • Overloading – A single symbol may refer to more than one algorithm – Each algorithm may have different type – Choice of algorithm determined by type context – Types of symbol may be arbitrarily different – + has types int*intint, real*realreal, ... Polymorphism: Haskell vs C++ • Haskell polymorphic function – Declarations (generally) require no type information – Type inference uses type variables – Type inference substitutes for variables as needed to instantiate polymorphic code • C++ function template – Programmer declares argument, result types of fctns – Programmers
    [Show full text]
  • Typedevil: Dynamic Type Inconsistency Analysis for Javascript
    TypeDevil: Dynamic Type Inconsistency Analysis for JavaScript Michael Pradel∗x, Parker Schuh∗, and Koushik Sen∗ ∗EECS Department, University of California, Berkeley xDepartment of Computer Science, TU Darmstadt Abstract—Dynamic languages, such as JavaScript, give pro- of type number with undefined, which is benign when grammers the freedom to ignore types, and enable them to write running the program in its default configuration but causes concise code in short time. Despite this freedom, many programs a crash with a slightly different configuration. Finding these follow implicit type rules, for example, that a function has a particular signature or that a property has a particular type. problems is difficult because they do not always lead to obvi- Violations of such implicit type rules often correlate with prob- ous signs of misbehavior when executing the programs. How lems in the program. This paper presents TypeDevil, a mostly can developers detect such problems despite the permissive dynamic analysis that warns developers about inconsistent types. nature of JavaScript? The key idea is to assign a set of observed types to each variable, All three examples in Figure 1 share the property that property, and function, to merge types based in their structure, and to warn developers about variables, properties, and functions a variable, property or function has multiple, inconsistent that have inconsistent types. To deal with the pervasiveness of types. In Figure 1a, variable dnaOutputStr holds both the polymorphic behavior in real-world JavaScript programs, we undefined value and string values. In Figure 1b, function present a set of techniques to remove spurious warnings and leftPad sometimes returns an object and sometimes returns to merge related warnings.
    [Show full text]
  • Notes - Javascript - Commonjs Modules
    Notes - JavaScript - CommonJS Modules Dr Nick Hayward A collection of notes &c. on plain JavaScript modules, in particular usage of CommonJS modules and Node.js. Contents Intro General usage Folders as modules package.json index.js require pattern Dynamic require for modules Module design Intro CommonJS is a module library and pattern popularised by Node.js. It is still in regular use for modern apps, both Node.js and client-side based apps. For client-side, we may use build tools, such as WebPack and Browserify, to bundle module dependencies for online usage in a browser-based environment. General usage In CommonJS, every file is a module. Each module has an implicit local scope, and the global scope needs to be accessed explicitly. The module code is wrapped in a function by the loading call, which provides this local scope. CommonJS modules may export a public interface for consumption in apps - dependencies are resolved using require function calls. require function calls are synchronous, returning the exposed interface for the required module. By default, functions in a module will be local to that module. We may then choose the functions, properties &c. to export in the public API for the module. e.g. // CONSTRUCTOR - create basic keyboard object for testing... function Keyboard(keyDetails) { ({ total: this.total, x: this.x, y: this.y, white: this.white, black: this.black } = keyDetails ); } module.exports = Keyboard; The function Keyboard is now available to other files (modules) by requiring the file, const keyboard = require('./basic1'); Local, relative modules may use the standard Unix path to define file access for the module relative to the application, e.g.
    [Show full text]
  • Venkat Subramaniam — «Functional Programming in Java
    Praise for Functional Programming in Java Venkat has done a superb job of bringing core functional language concepts to the Java ecosystem. Once you have peered into his looking glass of functional language design, it will be hard to go back to old-school imperative programming. ➤ Stephen Chin, Java technology ambassador and JavaOne content chair The introduction of lambdas to Java 8 has made me excited to use Java again, and Venkat’s combination of technical details and best practices make it easy to apply functional thinking to this new feature. ➤ Kimberly D. Barnes, senior software engineer Java 8 lambda expressions are an incredibly important new language feature. Every Java developer should read this excellent book and learn how to use them effectively. ➤ Chris Richardson, software architect and Java champion Many can explain lambdas; Venkat makes them useful. ➤ Kirk Pepperdine, Java performance tuning expert I highly recommend this book for Java programmers who want to get up to speed with functional programming in Java 8. It is a very concise book but still provides a comprehensive overview of Java 8. ➤ Nilanjan Raychaudhuri, author and developer at Typesafe Functional Programming in Java Harnessing the Power of Java 8 Lambda Expressions Venkat Subramaniam The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC.
    [Show full text]
  • Pharo by Example
    Portland State University PDXScholar Computer Science Faculty Publications and Computer Science Presentations 2009 Pharo by Example Andrew P. Black Portland State University, [email protected] Stéphane Ducasse Oscar Nierstrasz University of Berne Damien Pollet University of Lille Damien Cassou See next page for additional authors Let us know how access to this document benefits ouy . Follow this and additional works at: http://pdxscholar.library.pdx.edu/compsci_fac Citation Details Black, Andrew, et al. Pharo by example. 2009. This Book is brought to you for free and open access. It has been accepted for inclusion in Computer Science Faculty Publications and Presentations by an authorized administrator of PDXScholar. For more information, please contact [email protected]. Authors Andrew P. Black, Stéphane Ducasse, Oscar Nierstrasz, Damien Pollet, Damien Cassou, and Marcus Denker This book is available at PDXScholar: http://pdxscholar.library.pdx.edu/compsci_fac/108 Pharo by Example Andrew P. Black Stéphane Ducasse Oscar Nierstrasz Damien Pollet with Damien Cassou and Marcus Denker Version of 2009-10-28 ii This book is available as a free download from http://PharoByExample.org. Copyright © 2007, 2008, 2009 by Andrew P. Black, Stéphane Ducasse, Oscar Nierstrasz and Damien Pollet. The contents of this book are protected under Creative Commons Attribution-ShareAlike 3.0 Unported license. You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).
    [Show full text]