Key Takeaways
Treat JavaScript as a deliberately chosen subset, not a bag of features.
Choose what earns its place. JavaScript became widely used before its rough edges had been polished. Crockford’s answer is not to master every feature, but to select the parts that make programs more reliable and readable, and avoid the parts that invite confusion. Because removing old language features can break existing programs, programmers often have to create their own working subset.
A small language can do serious work. For a parser project, Crockford used a reduced version of JavaScript called Simplified JavaScript. It kept functions as values, objects that inherit from other objects, and concise object and array literals. That was enough to build a parser for JavaScript itself. The lesson is practical: define a subset your team can use consistently, rather than treating every available feature as equally valuable.
The book’s most durable move is to treat a programming language as a design space, not a checklist. This resembles the principle of least power in system design: use the least complicated mechanism that fully solves the problem, because each extra capability creates more ways to misunderstand or misuse it. A shared subset also reduces the mental translation required during code review. The limitation is that one person’s “good parts” can become another team’s constraint. A subset works best when its rules are explicit, justified, and revisited as the language and project change.
Use functions as values to build private state and asynchronous behavior.
Functions are building blocks. JavaScript functions can be stored, passed into other functions, returned, and used to retain access to the variables around them. That retained access is called a closure. A function can return methods that share a hidden counter, for example, while preventing unrelated code from changing the counter directly.
One tool, many jobs. A callback is a function supplied to run when an event occurs. Passing a callback to a network request lets the request return without freezing the user interface; the callback handles the response when it arrives. Functions can also solve recursive problems and save repeated work. In the book’s Fibonacci example, caching results cuts the total calls for values from 0 through 10 from 453 to 29. Currying creates a new function with some arguments already supplied.
Closures connect two ideas that are often taught separately: modular code and controlled access to state. A function is not merely a reusable instruction; it can also carry the environment it needs, which makes event-driven programs easier to organize. This is close to the capability-security idea that granting a function can grant a narrow permission without exposing all underlying data. The trade-off is that captured variables remain reachable while the function remains reachable. Closure design therefore benefits from deliberate lifetime management, especially when long-lived callbacks retain large objects.
Let objects inherit from objects, then customize only what differs.
Inheritance by delegation. In JavaScript’s prototype system, an object can retrieve properties from another object linked to it. This lookup through linked objects is called delegation. A new object can reuse the behavior of an existing one, then add or replace its own properties. The link affects lookup, not assignment: changing the new object does not change its prototype.
Know where a property lives. If a property is missing on the object itself, JavaScript searches its prototype chain. Adding a shared property to a prototype makes it visible to linked objects, while deleting an object’s own property can reveal an inherited one underneath. This reuse can reduce duplicated setup, but enumeration may expose inherited properties too. Use `hasOwnProperty` when the task requires only properties stored directly on the object.
Delegation is a useful mental model because it makes reuse concrete: an object can consult another object rather than belonging to a class hierarchy. That supports gradual specialization, where each new object states only its differences. It also makes shared behavior easy to update. The same dynamism creates a governance problem, however. A prototype is shared mutable state, so an apparently local change can affect many objects. Teams gain clarity when they distinguish deliberate shared behavior from instance-specific data and guard reflection or enumeration accordingly.
Prefer factories and composition to JavaScript's fragile class-shaped inheritance.
Return objects directly. Crockford favors a functional pattern in which a function accepts a specification, creates an object, adds methods, and returns it. Variables inside the function can hold private state, accessible only through the returned methods. A specialized factory can call a more general one, reuse its behavior, and add a feature of its own.
Assemble behavior from parts. The book also demonstrates adding event-handling methods to an existing object, rather than requiring that object to descend from a particular class. This suits JavaScript’s loose typing: an object is useful because of what it can do, not because of its ancestry. By contrast, constructor functions invoked with `new` can expose state and may cause damage if called without `new`, since `this` can point at the global object in the book’s language model.
Factories and composition emphasize observable behavior over lineage, a perspective shared by component-oriented design. They can make privacy and reuse easier to express than a deep hierarchy, especially when objects need combinations of capabilities that do not fit one parent-child tree. There is a cost: closure-based methods may be recreated for each instance, and private state can make debugging or inspection less direct. The design choice is therefore not privacy versus no privacy, but which state needs protection and which behavior is better shared openly.
Make JavaScript's hidden execution rules explicit before they make bugs.
Track what `this` means. In the book’s JavaScript model, calling a function as an object’s method binds `this` to that object. Calling the same function by itself binds `this` to the global object, a hazardous design choice. An inner function does not automatically inherit its outer method’s `this`; a common workaround is to save the outer value in a local variable. The `apply` method offers another way to choose the receiver explicitly.
Remember function scope. JavaScript’s braces group statements but do not create a new variable scope. Variables declared anywhere inside a function are visible throughout that function, so Crockford recommends declaring them at its start. The book also warns that a constructor called without `new` may modify globals, and that a line break after `return` can change the result.
These rules show why familiar syntax can be misleading: JavaScript looks like several C-family languages, yet its binding and scope behavior differ in important ways. Making the receiver explicit is a form of reducing ambient authority, since code is less likely to mutate an unintended global object. The precise bare-call behavior described here belongs to the book’s era and language assumptions, so it should not be copied uncritically into every modern runtime. The broader lesson remains sound: write down assumptions about scope and call context, then verify them with tools and tests.
Treat arrays and regular expressions as convenient, imperfect tools.
Arrays behave like objects. JavaScript arrays use integer-like property names and a special `length` value, rather than behaving exactly like fixed blocks of memory. An array can be sparse: setting its element at index 1,000,000 makes its length 1,000,001 even if it has only one stored element. Deleting an element leaves a hole; `splice` removes it and shifts later elements. Use a normal indexed loop when order matters, and provide a comparison function when sorting numbers.
Keep patterns readable. Regular expressions can search, validate, and extract text, but their compact syntax is easy to misread. Capturing groups store matched text; noncapturing groups only organize a pattern. Crockford recommends short, simple expressions, especially where validation or security depends on correctness. Overly complex patterns are harder to test, maintain, and port.
The shared theme is abstraction leakage: arrays and regular expressions look simpler than their internal rules make them. The array’s flexibility is productive for general-purpose collections, but sparse entries and inherited properties can violate assumptions borrowed from lower-level languages. Regular expressions offer a compact grammar, yet compactness is not the same as clarity. For critical validation, readable parsing steps and explicit tests can be safer than a single intricate pattern. Convenience should be judged against the assumptions a data structure or notation silently imposes.
Use strict conventions to compensate for JavaScript's permissive runtime.
Make mistakes visible. JavaScript’s loose typing and automatic conversions leave more responsibility with the programmer. The book recommends strict equality operators, `===` and `!==`, instead of coercive `==` and `!=`. It warns that `+` can add or concatenate depending on operand types, and that binary floating-point cannot represent many decimal fractions exactly. For money, the suggested remedy is to calculate in whole cents rather than decimal dollars.
Let discipline do the checking. Declare variables instead of accidentally creating globals, use braces around control-flow bodies, avoid switch fall-through, and do not rely on automatic semicolon insertion. JSLint checks a stricter subset and flags suspicious patterns, including undeclared names and risky style. It is an additional reviewer, not proof that a program is correct.
This is a form of defense in depth: when the language gives weak guarantees before execution, conventions and static checks can catch some errors earlier. The advice also reflects an important distinction between correctness and legibility. Braces and explicit comparisons do not make every bug impossible, but they make intent easier to inspect and accidental changes easier to detect. Linters can become noisy or overly prescriptive, so their rules deserve review. Their strongest use is as an agreed team contract that surfaces genuine ambiguity, not as a substitute for testing.
Keep executable code out of data, especially at browser boundaries.
Parse data as data. JSON is a text format for objects, arrays, strings, numbers, booleans, and `null`. Although its syntax resembles JavaScript object literals, it is not a program. The book warns against using `eval` to turn server text into a value and recommends `JSON.parse`, which rejects text that is not valid JSON.
Treat rendering as a security boundary. A server response can be malformed through incompetence as well as malice. If untrusted text is inserted as HTML, a script in that text may run with access to the page’s data, user interface, and network capabilities. Safer handling keeps data parsing separate from HTML execution and avoids treating arbitrary server-provided markup as harmless content.
The central security principle is code-data separation. A parser with a narrow grammar grants less authority than a general-purpose evaluator, which is a concrete application of least privilege. The warning about server incompetence is especially useful because security failures do not require a malicious source; fragile encoding or unsafe rendering can be enough. Parsing valid JSON is only one boundary, however. Parsed values still need validation, and rendered text still needs context-appropriate escaping. Trust should be assigned to specific operations, not inherited from a familiar format.
Measure each feature by the complexity it adds to every user.
Features have hidden costs. A language feature requires specification, implementation, testing, documentation, and ongoing maintenance. Features can also interact badly, increasing the number of behaviors a programmer must understand. A capability that helps a small group may impose learning and reliability costs on everyone else.
Simplicity takes design work. The book compares feature-heavy products to a microwave with many options but only a few that people regularly use. In software, the answer is not to reject every advanced feature. It is to ask whether the value is large enough to justify the permanent cost of supporting and explaining it. A smaller, coherent set of tools can be easier to learn and safer to combine than a larger collection of individually appealing options.
This argument anticipates a central problem in systems engineering: complexity grows not only with the number of components, but with their interactions. A feature’s cost is therefore partly externalized onto maintainers, reviewers, and users who never asked for it. Still, minimalism is not automatically humane. Removing a feature can shift complexity into workarounds, libraries, or custom code. The useful test is comparative: does the feature reduce total system complexity for its real users, or merely make the product look more capable?
Analysis
JavaScript: The Good Parts is not an attempt to document the whole language. It is an argument about professional judgment: programmers can improve a flawed language by adopting a deliberate subset and coding rules. That argument gives the book a coherent arc. It begins with selection, explains the expressive core in functions and prototype-linked objects, then shows how disciplined style, tooling, and secure data handling compensate for weak guarantees.
The book’s strongest insight is that language design is not finished when a standard is published. In practice, teams create local languages through conventions, APIs, and review rules. Crockford’s preferred subset is one such language, optimized for clarity and reduced risk. Closures, callbacks, and object delegation are presented not as novelty, but as ways to structure programs around the language’s actual strengths rather than importing assumptions from class-based languages.
Its sharp division between good and bad features is also a rhetorical simplification. A feature may be dangerous in one setting and valuable in another; coercion, dynamic objects, and regular expressions are not intrinsically useless. The useful question is whether their benefits exceed their interaction and maintenance costs in a particular codebase. Likewise, the book’s technical warnings describe the JavaScript edition and runtime landscape of 2008. They should be read as historically situated guidance, not as a complete account of present-day language behavior.
The lasting contribution is less a list of banned syntax than a method: identify where the language is predictable, constrain the rest, and make assumptions visible. Linting, explicit data parsing, small interfaces, and careful handling of shared state all turn that method into practice. The result is a view of programming language mastery that values selective fluency over encyclopedic feature knowledge.
Review Summary
JavaScript: The Good Parts receives mixed reviews but is generally well-regarded. Readers appreciate its concise explanation of JavaScript's best features and its honest critique of the language's flaws. Many find it eye-opening and valuable for experienced programmers new to JavaScript. However, some criticize its organization, outdated information, and occasionally confusing explanations. The book's opinionated style and focus on best practices are praised by some but seen as overly dogmatic by others. Overall, it's considered an important read for serious JavaScript developers, despite its limitations.
People Also Read
Glossary
Closure
Function with retained accessA closure is a function together with access to the variables in the scope where it was created. The inner function can continue using those variables even after the outer function has returned. Crockford uses closures for callbacks, private object state, and modules that expose selected operations without exposing their implementation.
Delegation
Prototype-based property lookupDelegation is the process by which an object obtains a property from another object linked to it as a prototype. If the first object does not contain the requested property, lookup continues along the prototype chain. Assignment still changes the object itself, rather than changing its prototype.
Differential inheritance
Reuse by specifying differencesDifferential inheritance creates a new object from an existing object and then adds or changes only the properties that differ. Instead of first defining a class hierarchy, the programmer starts with a useful object and specializes it. The pattern fits JavaScript’s prototype system, where objects can inherit directly from other objects.
Functional pattern
Factory with private stateThe functional pattern creates an object inside a function, optionally defines private variables and methods, adds public methods that can access that private state, and returns the object. It can support reuse by calling other object-producing functions and extending the returned object, without relying on constructor calls with new.
Durable object
Object protecting internal stateA durable object is an object whose internal state cannot be reached or changed except through the operations it intentionally exposes. In Crockford’s functional style, methods use closure-held variables rather than relying on publicly replaceable properties. The object may allow access to specific capabilities while keeping its underlying data private.
Memoization
Caching function resultsMemoization stores results from earlier function calls so repeated requests can return a saved result instead of recomputing it. Crockford demonstrates it with recursive Fibonacci calculations: a closure holds previously computed values, reducing the number of calls needed. A general memoizer can apply the same caching pattern to different recursive formulas.
Module
Interface with hidden implementationA module is a function or object that presents an interface while hiding its internal state and implementation. In JavaScript, Crockford builds modules with functions and closures: private variables remain inside a function scope, while returned methods provide controlled access. This also helps reduce reliance on global variables.
JSLint
JavaScript quality checkerJSLint is Crockford’s JavaScript syntax and code-quality tool. It checks source against a stricter subset and reports suspicious structures, style issues, and undeclared variables, among other problems. It can help make risky or ambiguous code visible, but it does not prove that a program is correct.
Simplified JavaScript
Reduced expressive subsetSimplified JavaScript is the reduced language Crockford defined for a parser project. It retains functions as first-class values, dynamic objects with prototype inheritance, and object and array literals. By excluding other language features, the subset was easier to describe and still expressive enough for building a parser for JavaScript.
JSON
Text format for dataJSON, or JavaScript Object Notation, is a language-independent text format for exchanging data. It represents objects, ordered arrays, strings, numbers, booleans, and null, using a deliberately small syntax. Its resemblance to JavaScript object literals does not make JSON executable code; the book recommends parsing it as data rather than evaluating it.
FAQ
What's "JavaScript: The Good Parts" about?
- Focus on JavaScript's strengths: The book highlights the most effective and efficient parts of JavaScript, aiming to help programmers use the language to its fullest potential.
- Target audience: It is intended for programmers who are either new to JavaScript or have been using it at a novice level and are ready to deepen their understanding.
- Not a beginner's guide: The book is not a comprehensive reference or a beginner's guide; it focuses on the essential parts of JavaScript that are most beneficial.
- Exclusion of bad parts: It deliberately excludes the problematic features of JavaScript to promote better programming practices.
Why should I read "JavaScript: The Good Parts"?
- Improve JavaScript skills: It helps programmers refine their skills by focusing on the most powerful and reliable features of JavaScript.
- Avoid common pitfalls: By highlighting the good parts, the book helps readers avoid the language's quirks and pitfalls.
- Enhance code quality: The book encourages writing cleaner, more maintainable, and more efficient code.
- Gain deeper insights: It provides insights into JavaScript's design and how to leverage its strengths effectively.
What are the key takeaways of "JavaScript: The Good Parts"?
- Embrace JavaScript's strengths: Focus on using JavaScript's functions, loose typing, and dynamic objects effectively.
- Avoid bad parts: Learn to identify and avoid JavaScript's problematic features, such as global variables and certain operators.
- Use of closures and prototypes: Understand and utilize closures and prototypal inheritance to write more expressive and powerful code.
- Adopt a disciplined style: Follow the book's style recommendations to write clear and consistent JavaScript code.
What are the best quotes from "JavaScript: The Good Parts" and what do they mean?
- "JavaScript is a language with more than its share of bad parts." This highlights the importance of being selective about which features to use.
- "JavaScript is a block of marble, and I chip away the features that are not beautiful until the language's true nature reveals itself." This metaphor emphasizes the book's approach of focusing on the language's strengths.
- "The good parts are good enough to compensate for the bad parts." This reassures readers that by focusing on the good parts, they can still achieve great results with JavaScript.
- "JavaScript is Lisp in C's clothing." This suggests that JavaScript's true power lies in its functional programming capabilities, similar to Lisp.
How does "JavaScript: The Good Parts" define the good parts of JavaScript?
- Functions as first-class objects: JavaScript treats functions as first-class citizens, allowing them to be passed around and manipulated like any other object.
- Dynamic objects with prototypal inheritance: JavaScript's objects are flexible and can inherit properties directly from other objects without the need for classes.
- Object and array literals: These provide a convenient and expressive way to create and manipulate data structures.
- Avoidance of bad parts: The book identifies and advises against using features that can lead to errors or poor code quality.
What are some of the bad parts of JavaScript according to "JavaScript: The Good Parts"?
- Global variables: They can lead to unpredictable behavior and are difficult to manage in large programs.
- Semicolon insertion: This can cause unexpected errors and should not be relied upon.
- Type coercion with == and !=: These operators can lead to confusing and unintended results due to automatic type conversion.
- The with statement: It can make code difficult to read and debug, and should be avoided.
How does "JavaScript: The Good Parts" suggest handling global variables?
- Minimize usage: The book advises minimizing the use of global variables to reduce complexity and potential conflicts.
- Single global variable: Create a single global variable to act as a namespace for your application, containing all other variables and functions.
- Use closures: Employ closures to encapsulate variables and functions, reducing reliance on global scope.
- Avoid implied globals: Always declare variables explicitly to prevent them from becoming global unintentionally.
What is the role of functions in "JavaScript: The Good Parts"?
- Modular unit: Functions are the fundamental modular unit in JavaScript, used for code reuse and information hiding.
- First-class objects: Functions can be stored in variables, passed as arguments, and returned from other functions.
- Closure: Functions can capture and remember the environment in which they were created, allowing for powerful programming patterns.
- Invocation patterns: The book discusses different ways to invoke functions, each with its own implications for the
thiskeyword.
How does "JavaScript: The Good Parts" explain prototypal inheritance?
- Class-free system: JavaScript uses a class-free object system where objects inherit directly from other objects.
- Prototype chain: Objects can delegate property access to their prototype, forming a chain that can be traversed for property lookup.
- Dynamic relationship: The prototype relationship is dynamic, meaning changes to a prototype are immediately reflected in all objects that inherit from it.
- Simplified inheritance: The book simplifies the process of creating objects with a specific prototype using a custom
Object.createmethod.
What style recommendations does "JavaScript: The Good Parts" provide?
- Consistent indentation: Use consistent indentation to improve code readability and structure.
- Use of blocks: Always use blocks with structured statements like
ifandwhileto prevent errors. - Avoid line breaks in expressions: Break lines after operators to avoid issues with semicolon insertion.
- Declare variables at the top: Declare all variables at the top of a function to avoid confusion due to JavaScript's lack of block scope.
How does "JavaScript: The Good Parts" suggest using JSON?
- Data interchange format: JSON is a lightweight format for exchanging data between programs, based on JavaScript's object literal notation.
- Use JSON.parse: Instead of
eval, useJSON.parseto safely parse JSON data and avoid security risks. - Avoid innerHTML with JSON: Be cautious when using JSON data with
innerHTMLto prevent script injection attacks. - Minimal and portable: JSON's design is minimal and portable, making it easy to implement and use across different programming languages.
What is JSLint and how is it related to "JavaScript: The Good Parts"?
- Code quality tool: JSLint is a tool that checks JavaScript code for potential problems and enforces a stricter subset of the language.
- Avoids bad parts: It helps programmers avoid JavaScript's bad parts by flagging problematic patterns and practices.
- Style enforcement: JSLint enforces the style recommendations from the book, promoting cleaner and more maintainable code.
- Global variable detection: It identifies undeclared variables to prevent accidental creation of global variables.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.