Share E-Book

The Joy of JavaScript (Luis Atencio)(Z-Library)

Author Luis Atencio

javascript
Language English

Whether building interactive browser-based applications or creating server-side applications in Node, JavaScript is the most widely used language for web programming. With new features, language improvements, paradigms, and potential use cases appearing regularly, there’s never been a more exciting time to be a JavaScript developer. In The Joy of JavaScript, author and JavaScript expert Luis Atencio teaches you key design concepts that lead to clean, lean, modular, and easy-to-maintain code. About the Technology JavaScript is at the heart of web applications on the browser side and, via the popular Node.js runtime, it often powers the server side too. Simply put, the web runs on JavaScript. About the book The Joy of JavaScript introduces techniques that turn JavaScript programmers into JavaScript pros. You’ll work with cutting edge APIs, language features, and coding styles to tackle tricky problems in an elegant manner. Along the way, you’ll practice good object design, drive business logic with functional thinking, and untangle complex data flows. What's inside • JavaScript’s objects and module system • Working with higher order functions • Identifying and creating composable software • Preparing for upcoming JavaScript features About the reader Written for experienced and passionate JavaScript developers. About the author Luis Atencio is a software engineer for Citrix Systems, author of Manning’s Functional Programming in JavaScript, and co-author of Manning’s RxJS in Action.

Format PDF
Size 6.5 MB
4
Views
0
Downloads
0.00
Total Donations
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
M A N N I N G Luis Atencio
Page 2
Constructor functions - Define object templates. - Require manual configuration of prototype references. Classes - Implement perceivable inheritance. - Take advantage of new features such as private and/or static properties. OLOO - Object-oriented does not mean class-oriented. - Treats objects as peers instead of parent-child. Closures - Allow functions to reference lexically scoped variables. - Necessary to implement most FP techniques. Higher-order functions - Allow functions to behave like objects. - Pass functions as arguments and as return values. compose/map/Functor - Assemble composable programs from simpler ones. - Functors are mappable objects (such as Array). - Mappables compose the way functions do. ECMAScript Modules - Standarize the module system for both client and server. - Use familiar import/export syntax. Symbols - Implement static hooking. - Some well-known symbols: @@iterator @@species @@toPrimitive Proxy/reflect - Implement dynamic hooking. - Override/redefine the behavior of an object. Async programming - Works with user input, HTTP requests, filesystem, and so on. - Supported by an event loop/callack queue architecture. Promises - Streamline async programming. - Reduce callback hell. Iterators/generators - Provide a way to enumerate a data structure or intermediate results of a funnction. - Use a common protocol {value: , done: }.any boolean Mixins - Implement dynamic object extension. - Compose whole objects from smaller ones. flatMap/ADT/Monad - Deal with side effects in a pure manner. - Implement railway-driven programming. Decorators - Weave custom code to run before and/or after an object’s methods. - Annotate a class/object declaratively. Observable streams - Compose asynchronous or event-based programs. - Handle finite or infinite sequences of data. Objects Functions Code Data - Automates prototype setup.
Page 3
The Joy of JavaScript
Page 4
(This page has no text content)
Page 5
The Joy of JavaScript LUIS ATENCIO MANN I NG SHELTER ISLAND
Page 6
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2021 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Development editor: Frances Lefkowitz Technical development editor: Peter Perlepes Manning Publications Co. Review editor: Aleks Dragosavljević 20 Baldwin Road Production editor: Deirdre S. Hiam PO Box 761 Proofreader: Melody Dolab Shelter Island, NY 1196 Technical proofreader: Jahred Love Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617295867 Printed in the United States of America
Page 7
To my children, Luke and Matthew, and my wife, Ana, for being my support pillars in life and helping me at every step of this journey. To all of my family for their love and support. Thank you.
Page 8
(This page has no text content)
Page 9
brief contents 1 ■ JavaScript reloaded 1 PART 1 OBJECTS .....................................................................21 2 ■ Inheritance-based object modeling 23 3 ■ Linked, compositional object models 42 PART 2 FUNCTIONS.................................................................71 4 ■ Writing composable, pure code 73 5 ■ Higher-kinded composition 114 PART 3 CODE. .......................................................................155 6 ■ ECMAScript Modules 157 7 ■ Hooked on metaprogramming 183 PART 4 DATA . .......................................................................223 8 ■ Linear async flows 225 9 ■ Streams programming 260vii
Page 10
(This page has no text content)
Page 11
contents preface xiii acknowledgments xv about this book xvii about the author xxi about the cover illustration xxii 1 JavaScript reloaded 1 1.1 Evolving JavaScript 4 1.2 Objects 5 1.3 Functions 7 1.4 Code 12 1.5 Data 13 1.6 Sample application: Blockchain 16 PART 1 OBJECTS ...........................................................21 2 Inheritance-based object modeling 23 2.1 Reviewing prototypal inheritance 24 Property resolution process 27 ■ Differential inheritance 29 2.2 Constructor functions 30 Functions as templates 30 ■ Sharing properties by using constructors and prototypes 31 2.3 Class-based inheritance 36ix
Page 12
CONTENTSx3 Linked, compositional object models 42 3.1 Types of object links 43 Implicit 43 ■ Explicit 44 3.2 OLOO 45 3.3 Understanding Object.assign 50 Object.assign uncovered 51 ■ Assignment vs definition 53 3.4 Assembling objects using mixin composition 54 Anatomy of a mixin 60 ■ Multiple inheritance and linearization 63 ■ Composing objects using Object.assign and the spread operator 65 3.5 Applying shared mixins to multiple objects 66 PART 2 FUNCTIONS.......................................................71 4 Writing composable, pure code 73 4.1 What is functional programming? 75 Functions as data 76 ■ The functional way 78 4.2 Functional versus imperative at a glance 79 4.3 Composition: The functional way 81 Working with side effects 84 ■ Decomposing complex code 87 4.4 Currying and closures 90 Curried function application 91 ■ The curry and composition dynamic duo 96 4.5 Working with immutable objects 100 4.6 Point-free coding 104 4.7 Imperative to functional transformation 106 4.8 Native function chains 111 5 Higher-kinded composition 114 5.1 Closing over data types 117 5.2 New Array APIs: {flat, flatMap} 122 Array.prototype.flat 122 ■ Array.prototype.flatMap 122 5.3 The map/compose correspondence 123 5.4 Universal contracts 124 Functors 124 ■ Monads 127
Page 13
CONTENTS xi5.5 Contextual validation with higher-order functions 131 Kinds of ADTs 131 ■ Choices 132 ■ Modeling success and failure with the Validation monad 134 ■ Composing with monads 138 ■ Higher-kinded composition with Validation 142 Point-free coding with monads 144 ■ Reducing complex data structures 146 ■ Third-party integration 149 5.6 Higher-kinded composition with method extraction and dynamic binding 150 PART 3 CODE..............................................................155 6 ECMAScript Modules 157 6.1 Past state of affairs 158 6.2 Module patterns 160 Object namespaces 161 ■ Immediately Invoked Function Expressions (IIFEs) 163 ■ IIFE mixins 164 ■ Factory functions 165 6.3 Static vs. dynamic module systems 167 6.4 ESM basics 170 Path specifiers 171 ■ Exporting 172 ■ Importing 174 A new extension in town 177 6.5 Benefits of ESM for tooling 178 Dead-code elimination and tree-shaking 178 ■ Faster property lookups 180 ■ Type-friendliness 181 7 Hooked on metaprogramming 183 7.1 Common uses of metaprogramming in JavaScript 184 7.2 JavaScript symbols 186 7.3 Symbol registries 188 Local registry 188 ■ Global registry 189 7.4 Practical application of symbols 190 Hidden properties 190 ■ Interoperability 191 Serialization 196 7.5 Well-known symbols 198 @@toStringTag 198 ■ @@isConcatSpreadable 199 @@species 200 ■ @@toPrimitive 203 ■ @@iterator 205 7.6 Dynamic introspection and weaving 211 Proxy objects 212 ■ The Reflect API 215 ■ Additional use cases 216 7.7 Implementing method decorators 218
Page 14
CONTENTSxiiPART 4 DATA ..............................................................223 8 Linear async flows 225 8.1 Architecture at a glance 226 8.2 JavaScript as promised 228 Principle of data locality 231 ■ Are promises algebraic? 231 Fluent chaining 234 ■ Promises in the wild 242 8.3 API review: Promise combinators 244 Promise.all 246 ■ Promise.race 247 ■ Promise.allSettled 247 Promise.any 248 8.4 async made easy 249 8.5 async iteration 252 8.6 Top-level await 257 9 Streams programming 260 9.1 Iterables and Iterators 262 Iterable protocol 262 ■ Iterator protocol 263 ■ Examples 263 9.2 Generators 266 To return or to yield 266 ■ Creating iterable objects 267 Async generators 269 9.3 Working with data streams 273 What is a stream? 274 ■ Implementing a streamable array 275 9.4 Welcoming a new native: Observable 278 What is an Observable? 279 ■ Creating custom observables 281 Building your own reactive toolkit 282 ■ Observable mixin extension 288 ■ Representing push streams with generators 290 Pipeable operators 295 ■ Streamifying objects 297 ■ Dynamic streamification 300 9.5 Closing thoughts 304 appendix A Configuring Babel 306 appendix B Typed JavaScript<T> 308 index 325
Page 15
preface I learned to program computers in a traditional, academic way. The universities I attended based their curricula primarily on class-oriented languages such as Java, C++, and C#. When I came out of those programs, my brain was trained to think that classes were the best (maybe even only) way to design programs and that anything else would be an abomination. Years later, like any other developer in the world, I stumbled onto JavaScript—I should say jQuery, because at the time, jQuery was JavaScript. JavaScript was diametri- cally opposite to most of what I had learned. I struggled with every fundamental aspect of programming, including representing domain models, encapsulating behav- ior and data into logical modules, and dealing with events and asynchronous func- tions. I said to myself, Fine, let’s use jQuery and a slew of third-party libraries to “fix the language” and forget all about this. But JavaScript didn’t need fixing: I needed to get fixed. I knew I couldn’t get away from it. Because JavaScript was pretty much everywhere, it was only a matter of time before I’d stumble onto it again, so I decided to explore it more deeply. Learning about its prototype mechanism and closures showed me the true meaning of object-oriented programming. When Alan Kay invented this term in the early 2000s, he wanted to bring together concepts such as message-passing (objects passing or sending messages to other objects), encapsulation (exposing only what’s necessary), and dynamic linking (resolving properties of an object by name at runtime). Unlike all the other languages I’d learned, JavaScript had these principles deeply rooted in its design; more important,xiii
Page 16
PREFACExivthe concepts were easily accessible to developers. Then it dawned on me that I finally understood programming. Armed with newfound motivation, I continued learning about JavaScript and found higher-order functions, which opened my eyes to functional programming and composable software. Suddenly, programming wasn’t frustrating; it was a joy. This real- ization propelled my career as an author of books such as Functional Programming in JavaScript (Manning, 2016), RxJS in Action (Manning, 2017), and now The Joy of JavaScript (Manning, 2021). This book is for developers who, like me, have had the good fortune to learn about amazing features such as closures, prototypes, and higher-order functions, and want to take them to the next level so that they can enjoy working with JavaScript every sin- gle day. The Joy of JavaScript shows what the language has to offer on its own, without any third-party libraries and frameworks. Due to the sheer number of topics surround- ing JavaScript, this book doesn’t spend much time digging into basic concepts (but offers good resources for them); neither is it a guide to writing ECMAScript 2019, 2020, and so on. Rather, it gives you a close-up view of exciting topics, trends, and techniques that will allow you to master areas of the language that you probably didn’t know existed. As a bonus, the book introduces you to some additions to the language that may land in the years to come. It’s valuable to learn about these proposals so that you’ll understand where the language is headed and how it’s evolving. Writing this book helped me get through these uncertain and anxious times, and I sincerely hope that you find the same joy in reading it that I did writing it. While work- ing on this manuscript, I gained a fresh perspective on programming as a whole, and I hope that it does the same for you.
Page 17
acknowledgments This book was a lot of work. But I believe that all that work resulted in a fine book that nicely complements what’s already out there, and I hope that you will think so as well. I’d like to thank quite a few people for helping me along the way. First and foremost, I want to thank my wife, Ana. You’ve always supported me, always patiently taking care of things (including our two amazing boys, Luke and Mat- thew) while I struggled to get this book done. You always made me believe I could fin- ish it. I love you. Next, I’d like to acknowledge my longtime, flawless editor at Manning, Frances Lefkowitz. Thank you for working with me, guiding me every step of the way, and mak- ing the writing process delightful (not to mention bearable). Your commitment to the quality of this book made it better for everyone who will read it. Thanks as well to all the other folks at Manning who worked with me on the production and promotion of the book: Deirdre Hiam, and Melody Dolab. It was truly a team effort. I’d also like to thank the reviewers who took the time to read my manuscript at var- ious stages during its development and who provided invaluable feedback: Al Peze- wski, Alberto Ciarlanti, Amit Lamba, Birnou Sébarte, Daniel Posey, Daniel Bretoi, Dary Merckens, Dennis Reil, Didier Garcia, Edwin Kwok, Foster Haines, Francesco Strazzullo, Gabriel Wu, Jacob Romero, Joe Justesen, Jon Guenther, Julien Pohie, Kevin Norman D. Kapchan, Kimberly Winston-Jackson, Konstantinos Leimonis, Jahred Love, Lora Vardarova, Matteo Gildone, Miranda Whurr, Nate Clark, Pietro Maffi, Rance Shields, Ray Booysen, Richard Michaels, Sachin Singhi, Satej Kumar Sahu, Srihari Sridharan, Ubaldo Pescatore, and Víctor M. Pérez.xv
Page 18
ACKNOWLEDGMENTSxvi Special thanks to Gleb Bahmutov (https://twitter.com/bahmutov), vice president of engineering at Cypress.io (https://www.cypress.io), and James Sinclair (https:// twitter.com/jrsinclair) for their insightful review of the book and code. Gleb and James are amazing JavaScript advocates, and I highly recommend that you follow their work. Thanks also to my brother, Carlos, who took the time to read the book and offered lots of important, constructive feedback. Finally, I’m standing on the shoulders of giants. Thank you, Kyle Simpson, for teaching us JavaScript the right way in your book series You Don’t Know JS (https:// github.com/getify/You-Dont-Know-JS), and to Eric Elliot for his unique views on com- posable software (https://leanpub.com/composingsoftware). Also, thanks to Brendan Eich, without whom JavaScript would not exist. You make work a joy!
Page 19
about this book JavaScript fatigue is real—not only because programmers have more than a million NPM packages to choose from, but also because they have an equal amount of online resources to turn to for information and guidance. The Joy of JavaScript was written to synthesize some of the most cutting-edge and exciting developments in the JavaScript language, to help you go beyond the basics and reach the next level. The book begins by comparing and contrasting object-oriented modeling techniques that highlight JavaScript’s prototype chains and dynamic linking. Then it puts the spotlight on higher-order functions and on using JavaScript’s functional programming capabilities to arrive at truly composable software—a theme that in one way or another permeates the entire book. Next, the books tackles static and dynamic separation of concerns with modules and metaprogramming, respectively. The book ends with a discussion of ways to handle asynchronous flows of data streams effectively. My hope is that this four-part journey will help turn fatigue into joy. Who should read this book The Joy of JavaScript is for professional developers who already possess a solid founda- tion and are looking to expand their breadth of knowledge into other parts of the language--including aspects they may have seen or heard about but never had the oppor- tunity or time to learn. Although the book targets intermediate to advanced develop- ers, it gently introduces some of the most difficult topics, so it’s also suitable for a beginner enthusiast who is passionate and willing to catch up on the side.xvii
Page 20
ABOUT THIS BOOKxviiiHow this book is organized Each chapter contributes to the book’s goal of showing how to build up software from simple, composable pieces. The chapters are grouped in four parts, with each part looking at JavaScript from a different angle: objects, functions, code, and data. The book’s four parts cover nine chapters and should be read in order, as each chapter and part builds on the previous one. To give you a fuller idea of what’s in store, here’s a summary of each part. Part 1: Objects The first part sheds light on JavaScript’s object system. Syntactical support for class declarations gives you a clean, simple way to establish inheritance relationships in your domain model so that you can take advantage of proper data encapsulation and create highly cohesive, well-structured domains. Despite many advances that added class-oriented artifacts (such as classes, private properties, and inheritance), JavaScript is far from being a class-oriented language; in reality, it’s quite the opposite. The underlying prototype mechanism makes JavaScript’s object system incredibly mallea- ble, versatile, and far more dynamic than that of other languages. This part exposes you to techniques that help you build and instantiate your domain model entities, understanding the pros and cons of each approach. In this part, you’ll learn that although classes have a place in JavaScript, they are not the only ways to model your objects and certainly don’t reflect the way JavaScript works. To be proficient in the language, you must understand how the object system works. Part 2: Functions After defining the shape of our objects in the first part, in part 2 we connect them by using pure functions and composition. Functions bring the fun to The Joy of JavaScript. JavaScript has powerful functional programming capabilities that make functions the main units of computation. Believe it or not, functions have always been the strongest parts of JavaScript. The language’s support for higher-order functions is the key to writing modular, composable, and maintainable software. In this part, you will learn how to use functional programming (FP) principles cen- tered on immutability, purity, and algebraic data types (ADT) to drive the business logic of your application forward. You place functions front and center in your design to take advantage of JavaScript’s strongest feature: higher-order functions. By this point, you’ll be well versed in modern JavaScript idioms, and you’ll have taken a peek at slick new language features such as the pipeline and bind operators. Part 3: Code An area in which JavaScript was lacking was a standardized, official module system. Many attempts were made over the years to solve this problem, but nothing worked well across client/server platforms. By borrowing the best from all these attempts, JavaScript introduced the ECMAScript Modules (ESM) system—aka ES6 modules.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Support Author

0.00
Total Amount (¥)
0
Donation Count
Please enter an amount Minimum ¥1

You will be redirected to Alipay to complete payment, then return here.

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List