See also: JavaScript Bibliography and Bibliography of JavaScript Libraries and Web Frameworks
Se: Eloquent JavaScript: A Modern Introduction to Programming, 3rd Edition, by Marijn Haverbeke, 2019, B07C96Q217 (EloJS)
Fair Use Source: B07C96Q217 (EloJS)
About This Book:
Completely revised and updated, this best-selling introduction to programming in JavaScript focuses on writing real applications.
JavaScript lies at the heart of almost every modern web application, from social apps like Twitter to browser-based game frameworks like Phaser and Babylon. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications.
This much anticipated and thoroughly revised third edition of Eloquent JavaScript dives deep into the JavaScript language to show you how to write beautiful, effective code. It has been updated to reflect the current state of Java¬Script and web browsers and includes brand-new material on features like class notation, arrow functions, iterators, async functions, template strings, and block scope. A host of new exercises have also been added to test your skills and keep you on track.
As with previous editions, Haverbeke continues to teach through extensive examples and immerses you in code from the start, while exercises and full-chapter projects give you hands-on experience with writing your own programs. You start by learning the basic structure of the JavaScript language as well as control structures, functions, and data structures to help you write basic programs. Then you’ll learn about error handling and bug fixing, modularity, and asynchronous programming before moving on to web browsers and how JavaScript is used to program them. As you build projects such as an artificial life simulation, a simple programming language, and a paint program, you’ll learn how to:
– Understand the essential elements of programming, including syntax, control, and data
– Organize and clarify your code with object-oriented and functional programming techniques
– Script the browser and make basic web applications
– Use the DOM effectively to interact with browsers
– Harness Node.js to build servers and utilities
Isn’t it time you became fluent in the language of the Web?
* All source code is available online in an interactive sandbox, where you can edit the code, run it, and see its output instantly.
Reviews:
PRAISE FOR THE FIRST AND SECOND EDITIONS OF ELOQUENT JAVASCRIPT
“Provides some of the best explanations of programming concepts that I’ve ever read.” —SANDRA HENRY-STOCKER, IT WORLD
“If you choose to start your JavaScript journey with this book, it can quickly teach you a lot of technical information and also programming wisdom.” —MICHAEL J. ROSS, WEB DEVELOPER AND SLASHDOT CONTRIBUTOR
“I became a better architect, author, mentor and developer because of this book. It deserves to share shelf space with Flannagan and Crockford.” —ANGUS CROLL, TWITTER DEVELOPER
“The best introduction into any programming language and programming overall. Period.” —JAN LEHNARDT, CO-CREATOR OF HOODIE AND ORGANIZER OF JSCONF EU
“This is the book I give out when people ask me how to learn proper JavaScript.” —CHRIS WILLIAMS, ORGANIZER OF JSCONF US
“One of the best JavaScript books I’ve read.” —REY BANGO, JQUERY TEAM MEMBER AND CLIENT-WEB COMMUNITY PROGRAM MANAGER AT MICROSOFT
“A really good guide to JavaScript; but even more than that, this book is a great guide to programming.” —BEN NADEL, CHIEF SOFTWARE ENGINEER AT EPICENTER CONSULTING
“A good book, suitable for those without experience in JavaScript and even those without programming experience.” —NICHOLAS ZAKAS, AUTHOR OF HIGH PERFORMANCE JAVA SCRIPT AND THE PRINCIPLES OF OBJECT-ORIENTED JAVA SCRIPT
“If you’re new to JavaScript, the first thing I’d recommend you do is visit Eloquent JavaScript and check out Marijn Haverbeke’s introduction to the language.” —CNET UK
About the Author:
Marijn Haverbeke is a programming language enthusiast and polyglot. He’s worked on a wide range of software systems, from databases to compilers to editors. He runs a small business around his open source projects.
Book Details:
- ASIN: B07C96Q217
- ISBN-10: 1593279507
- ISBN-13: 978-1593279509
- Publisher: No Starch Press; 3rd edition (December 4, 2018)
- Publication date: December 4, 2018
- Print length: 474 pages
Table of Contents:
BRIEF CONTENTS
Introduction
PART I: LANGUAGE
Chapter 1: Values, Types, and Operators
Chapter 2: Program Structure
Chapter 3: Functions
Chapter 4: Data Structures: Objects and Arrays
Chapter 5: Higher-Order Functions
Chapter 6: The Secret Life of Objects
Chapter 7: Project: A Robot
Chapter 8: Bugs and Errors
Chapter 9: Regular Expressions
Chapter 10: Modules
Chapter 11: Asynchronous Programming
Chapter 12: Project: A Programming Language
PART II: BROWSER
Chapter 13: JavaScript and the Browser
Chapter 14: The Document Object Model
Chapter 15: Handling Events
Chapter 16: Project: A Platform Game
Chapter 17: Drawing on Canvas
Chapter 18: HTTP and Forms
Chapter 19: Project: A Pixel Art Editor
PART III: NODE
Chapter 20: Node.js
Chapter 21: Project: Skill-Sharing Website
Chapter 22: JavaScript and Performance
Exercise Hints
Index
CONTENTS IN DETAIL
INTRODUCTION
On Programming
Why Language Matters
What Is JavaScript?
Code, and What to Do with It
Overview of This Book
Typographic Conventions
PART I: LANGUAGE
1
VALUES, TYPES, AND OPERATORS
Values
Numbers
Arithmetic
Special Numbers
Strings
Unary Operators
Boolean Values
Comparison
Logical Operators
Empty Values
Automatic Type Conversion
Short-Circuiting of Logical Operators
Summary
2
PROGRAM STRUCTURE
Expressions and Statements
Bindings
Binding Names
The Environment
Functions
The console.log Function
Return Values
Control Flow
Conditional Execution
while and do Loops
Indenting Code
for Loops
Breaking Out of a Loop
Updating Bindings Succinctly
Dispatching on a Value with switch
Capitalization
Comments
Summary
Exercises
Looping a Triangle
FizzBuzz
Chessboard
3
FUNCTIONS
Defining a Function
Bindings and Scopes
Nested Scope
Functions as Values
Declaration Notation
Arrow Functions
The Call Stack
Optional Arguments
Closure
Recursion
Growing Functions
Functions and Side Effects
Summary
Exercises
Minimum
Recursion
Bean Counting
4
DATA STRUCTURES: OBJECTS AND ARRAYS
The Weresquirrel
Data Sets
Properties
Methods
Objects
Mutability
The Lycanthrope’s Log
Computing Correlation
Array Loops
The Final Analysis
Further Arrayology
Strings and Their Properties
Rest Parameters
The Math Object
Destructuring
JSON
Summary
Exercises
The Sum of a Range
Reversing an Array
A List
Deep Comparison
5
HIGHER-ORDER FUNCTIONS
Abstraction
Abstracting Repetition
Higher-Order Functions
Script Data Set
Filtering Arrays
Transforming with map
Summarizing with reduce
Composability
Strings and Character Codes
Recognizing Text
Summary
Exercises
Flattening
Your Own Loop
Everything
Dominant Writing Direction
6
THE SECRET LIFE OF OBJECTS
Encapsulation
Methods
Prototypes
Classes
Class Notation
Overriding Derived Properties
Maps
Polymorphism
Symbols
The Iterator Interface
Getters, Setters, and Statics
Inheritance
The instanceof Operator
Summary
Exercises
A Vector Type
Groups
Iterable Groups
Borrowing a Method
7
PROJECT: A ROBOT
Meadowfield
The Task
Persistent Data
Simulation
The Mail Truck’s Route
Pathfinding
Exercises
Measuring a Robot
Robot Efficiency
Persistent Group
8
BUGS AND ERRORS
Language
Strict Mode
Types
Testing
Debugging
Error Propagation
Exceptions
Cleaning Up After Exceptions
Selective Catching
Assertions
Summary
Exercises
Retry
The Locked Box
9
REGULAR EXPRESSIONS
Creating a Regular Expression
Testing for Matches
Sets of Characters
Repeating Parts of a Pattern
Grouping Subexpressions
Matches and Groups
The Date Class
Word and String Boundaries
Choice Patterns
The Mechanics of Matching
Backtracking
The replace Method
Greed
Dynamically Creating RegExp Objects
The search Method
The lastIndex Property
Looping Over Matches
Parsing an INI File
International Characters
Summary
Exercises
Regexp Golf
Quoting Style
Numbers Again
10
MODULES
Modules as Building Blocks
Packages
Improvised Modules
Evaluating Data as Code
CommonJS
ECMAScript Modules
Building and Bundling
Module Design
Summary
Exercises
A Modular Robot
Roads Module
Circular Dependencies
11
ASYNCHRONOUS PROGRAMMING
Asynchronicity
Crow Tech
Callbacks
Promises
Failure
Networks Are Hard
Collections of Promises
Network Flooding
Message Routing
Async Functions
Generators
The Event Loop
Asynchronous Bugs
Summary
Exercises
Tracking the Scalpel
Building Promise.all
12
PROJECT: A PROGRAMMING LANGUAGE
Parsing
The Evaluator
Special Forms
The Environment
Functions
Compilation
Cheating
Exercises
Arrays
Closure
Comments
Fixing Scope
PART II: BROWSER
13
JAVASCRIPT AND THE BROWSER
Networks and the Internet
The Web
HTML
HTML and JavaScript
In the Sandbox
Compatibility and the Browser Wars
14
THE DOCUMENT OBJECT MODEL
Document Structure
Trees
The Standard
Moving Through the Tree
Finding Elements
Changing the Document
Creating Nodes
Attributes
Layout
Styling
Cascading Styles
Query Selectors
Positioning and Animating
Summary
Exercises
Build a Table
Elements by Tag Name
The Cat’s Hat
15
HANDLING EVENTS
Event Handlers
Events and DOM Nodes
Event Objects
Propagation
Default Actions
Key Events
Pointer Events
Mouse Clicks
Mouse Motion
Touch Events
Scroll Events
Focus Events
Load Event
Events and the Event Loop
Timers
Debouncing
Summary
Exercises
Balloon
Mouse Trail
Tabs
16
PROJECT: A PLATFORM GAME
The Game
The Technology
Levels
Reading a Level
Actors
Encapsulation as a Burden
Drawing
Motion and Collision
Actor Updates
Tracking Keys
Running the Game
Exercises
Game Over
Pausing the Game
A Monster
17
DRAWING ON CANVAS
SVG
The Canvas Element
Lines and Surfaces
Paths
Curves
Drawing a Pie Chart
Text
Images
Transformation
Storing and Clearing Transformations
Back to the Game
Choosing a Graphics Interface
Summary
Exercises
Shapes
The Pie Chart
A Bouncing Ball
Precomputed Mirroring
18
HTTP AND FORMS
The Protocol
Browsers and HTTP
Fetch
HTTP Sandboxing
Appreciating HTTP
Security and HTTPS
Form Fields
Focus
Disabled Fields
The Form as a Whole
Text Fields
Checkboxes and Radio Buttons
Select Fields
File Fields
Storing Data Client-Side
Summary
Exercises
Content Negotiation
A JavaScript Workbench
Conway’s Game of Life
19
PROJECT: A PIXEL ART EDITOR
Components
The State
DOM Building
The Canvas
The Application
Drawing Tools
Saving and Loading
Undo History
Let’s Draw
Why Is This So Hard?
Exercises
Keyboard Bindings
Efficient Drawing
Circles
Proper Lines
PART III: NODE
20
NODE.JS
Background
The node Command
Modules
Installing with NPM
Package Files
Versions
The File System Module
The HTTP Module
Streams
A File Server
Summary
Exercises
Search Tool
Directory Creation
A Public Space on the Web
21
PROJECT: SKILL-SHARING WEBSITE
Design
Long Polling
HTTP Interface
The Server
Routing
Serving Files
Talks as Resources
Long Polling Support
The Client
HTML
Actions
Rendering Components
Polling
The Application
Exercises
Disk Persistence
Comment Field Resets
22
JAVASCRIPT AND PERFORMANCE
Staged Compilation
Graph Layout
Defining a Graph
Force-Directed Layout
Avoiding Work
Profiling
Function Inlining
Creating Less Garbage
Garbage Collection
Dynamic Types
Summary
Exercises
Pathfinding
Timing
Optimizing
EXERCISE HINTS
Chapter 2: Program Structure
Looping a Triangle
FizzBuzz
Chessboard
Chapter 3: Functions
Minimum
Recursion
Bean Counting
Chapter 4: Data Structures: Objects and Arrays
The Sum of a Range
Reversing an Array
A List
Deep Comparison
Chapter 5: Higher-Order Functions
Everything
Dominant Writing Direction
Chapter 6: The Secret Life of Objects
A Vector Type
Groups
Iterable Groups
Borrowing a Method
Chapter 7: Project: A Robot
Measuring a Robot
Robot Efficiency
Persistent Group
Chapter 8: Bugs and Errors
Retry
The Locked Box
Chapter 9: Regular Expressions
Quoting Style
Numbers Again
Chapter 10: Modules
A Modular Robot
Roads Module
Circular Dependencies
Chapter 11: Asynchronous Programming
Tracking the Scalpel
Building Promise.all
Chapter 12: Project: A Programming Language
Arrays
Closure
Comments
Fixing Scope
Chapter 14: The Document Object Model
Build a Table
Elements by Tag Name
The Cat’s Hat
Chapter 15: Handling Events
Balloon
Mouse Trail
Tabs
Chapter 16: Project: A Platform Game
Pausing the Game
A Monster
Chapter 17: Drawing on Canvas
Shapes
The Pie Chart
A Bouncing Ball
Precomputed Mirroring
Chapter 18: HTTP and Forms
Content Negotiation
A JavaScript Workbench
Conway’s Game of Life
Chapter 19: Project: A Pixel Art Editor
Keyboard Bindings
Efficient Drawing
Circles
Proper Lines
Chapter 20: Node.js
Search Tool
Directory Creation
A Public Space on the Web
Chapter 21: Project: Skill-Sharing Website
Disk Persistence
Comment Field Resets
Chapter 22: JavaScript and Performance
Pathfinding
Optimizing
INDEX
INTRODUCTION
This is a book about instructing computers. Computers are about as common as screwdrivers today, but they are quite a bit more complex, and making them do what you want them to do isn’t always easy.
If the task you have for your computer is a common, well-understood one, such as showing you your email or acting like a calculator, you can open the appropriate application and get to work. But for unique or open-ended tasks, there probably is no application.
That is where programming may come in. Programming is the act of constructing a program—a set of precise instructions telling a computer what to do. Because computers are dumb, pedantic beasts, programming is fundamentally tedious and frustrating.
Fortunately, if you can get over that fact, and maybe even enjoy the rigor of thinking in terms that dumb machines can deal with, programming can be rewarding. It allows you to do things in seconds that would take forever by hand. It is a way to make your computer tool do things that it couldn’t do before. And it provides a wonderful exercise in abstract thinking.
Most programming is done with programming languages. A programming language is an artificially constructed language used to instruct computers. It is interesting that the most effective way we’ve found to communicate with a computer borrows so heavily from the way we communicate with each other. Like human languages, computer languages allow words and phrases to be combined in new ways, making it possible to express ever new concepts.
At one point language-based interfaces, such as the BASIC and DOS prompts of the 1980s and 1990s, were the main method of interacting with computers. They have largely been replaced with visual interfaces, which are easier to learn but offer less freedom. Computer languages are still there, if you know where to look. One such language, JavaScript, is built into every modern web browser and is thus available on almost every device.
This book will try to make you familiar enough with this language to do useful and amusing things with it.
On Programming
Besides explaining JavaScript, I will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are simple and clear, but programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you might just get lost in it.
There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be combined in ways that require you to make additional connections.
It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and make sure you read and understand the example programs and exercises. Learning is hard work, but everything you learn is yours and will make subsequent learning easier.
“When action grows unprofitable, gather information; when information grows unprofitable, sleep. —Ursula K. Le Guin, The Left Hand of Darkness
A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer’s memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short. A superficially fitting one is that of a machine—lots of separate parts tend to be involved, and to make the whole thing tick, we have to consider the ways in which these parts interconnect and contribute to the operation of the whole.
A computer is a physical machine that acts as a host for these immaterial machines. Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can ingeniously combine an enormous number of these simple actions to do very complicated things.
A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands.
But without care, a program’s size and complexity will grow out of control, confusing even the person who created it. Keeping programs under control is the main problem of programming. When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued—made simple in its complexity.
Some programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules (“best practices”) prescribing the form programs should have and carefully stay within their safe little zone.
This is not only boring, it is ineffective. New problems often require new solutions. The field of programming is young and still developing rapidly, and it is varied enough to have room for wildly different approaches. There are many terrible mistakes to make in program design, and you should go ahead and make them so that you understand them. A sense of what a good program looks like is developed in practice, not learned from a list of rules.