You are previewing Maintainable JavaScript.

Maintainable JavaScript

Cover of Maintainable JavaScript by Nicholas C. Zakas Published by O'Reilly Media, Inc.
  1. Maintainable JavaScript
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Introduction
  4. Preface
    1. Conventions Used in This Book
    2. Using Code Examples
    3. Safari® Books Online
    4. How to Contact Us
  5. I. Style Guidelines
    1. 1. Basic Formatting
      1. Indentation Levels
      2. Statement Termination
      3. Line Length
      4. Line Breaking
      5. Blank Lines
      6. Naming
      7. Literal Values
    2. 2. Comments
      1. Single-Line Comments
      2. Multiline Comments
      3. Using Comments
      4. Documentation Comments
    3. 3. Statements and Expressions
      1. Brace Alignment
      2. Block Statement Spacing
      3. The switch Statement
      4. The with Statement
      5. The for Loop
      6. The for-in Loop
    4. 4. Variables, Functions, and Operators
      1. Variable Declarations
      2. Function Declarations
      3. Function Call Spacing
      4. Immediate Function Invocation
      5. Equality
      6. eval()
      7. Primitive Wrapper Types
  6. II. Programming Practices
    1. 5. Loose Coupling of UI Layers
      1. What Is Loose Coupling?
      2. Keep JavaScript Out of CSS
      3. Keep CSS Out of JavaScript
      4. Keep JavaScript Out of HTML
      5. Keep HTML Out of JavaScript
    2. 6. Avoid Globals
      1. The Problems with Globals
      2. Accidental Globals
      3. The One-Global Approach
      4. The Zero-Global Approach
    3. 7. Event Handling
      1. Classic Usage
      2. Rule #1: Separate Application Logic
      3. Rule #2: Don’t Pass the Event Object Around
    4. 8. Avoid Null Comparisons
      1. Detecting Primitive Values
      2. Detecting Reference Values
      3. Detecting Properties
    5. 9. Separate Configuration Data from Code
      1. What Is Configuration Data?
      2. Externalizing Configuration Data
      3. Storing Configuration Data
    6. 10. Throw Your Own Errors
      1. The Nature of Errors
      2. Throwing Errors in JavaScript
      3. Advantages of Throwing Errors
      4. When to Throw Errors
      5. The try-catch Statement
      6. Error Types
    7. 11. Don’t Modify Objects You Don’t Own
      1. What Do You Own?
      2. The Rules
      3. Better Approaches
      4. A Note on Polyfills
      5. Preventing Modification
    8. 12. Browser Detection
      1. User-Agent Detection
      2. Feature Detection
      3. Avoid Feature Inference
      4. Avoid Browser Inference
      5. What Should You Use?
  7. III. Automation
    1. 13. File and Directory Structure
      1. Best Practices
      2. Basic Layout
    2. 14. Ant
      1. Installation
      2. The Build File
      3. Running the Build
      4. Target Dependencies
      5. Properties
      6. Buildr
    3. 15. Validation
      1. Finding Files
      2. The Task
      3. Improving the Target
      4. Other Improvements
      5. Buildr Task
    4. 16. Concatenation and Baking
      1. The Task
      2. Line Endings
      3. Headers and Footers
      4. Baking Files
    5. 17. Minification and Compression
      1. Minification
      2. Compression
    6. 18. Documentation
      1. JSDoc Toolkit
      2. YUI Doc
    7. 19. Automated Testing
      1. YUI Test Selenium Driver
      2. Yeti
      3. PhantomJS
      4. JsTestDriver
    8. 20. Putting It Together
      1. Missing Pieces
      2. Planning the Build
      3. Using a CI System
  8. A. JavaScript Style Guide
    1. Indentation
    2. Line Length
    3. Primitive Literals
    4. Operator Spacing
    5. Parentheses Spacing
    6. Object Literals
      1. Single-Line Comments
      2. Multiline Comments
      3. Comment Annotations
    8. Variable Declarations
    9. Function Declarations
    10. Naming
    11. Strict Mode
    12. Assignments
    13. Equality Operators
    14. Ternary Operator
    15. Statements
      1. Simple Statements
      2. return Statement
      3. Compound Statements
      4. if Statement
      5. for Statement
      6. while Statement
      7. do Statement
      8. switch Statement
      9. try Statement
    16. White Space
    17. Things to Avoid
  9. B. JavaScript Tools
    1. Build Tools
    2. Documentation Generators
    3. Linting Tools
    4. Minification Tools
    5. Testing Tools
  10. Index
  11. About the Author
  12. Colophon
  13. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  14. Copyright


The professionalization of web development has been a difficult journey because of our disparate beginnings. Even those who end up at large companies such as Yahoo! inevitably began on their own, hacking around. Perhaps you were even “the web guy” at a small company and could do pretty much whatever you wanted. When the large companies started tapping this previously undiscovered resource, it brought a lot of hackers into a corporate environment, where they were met with constraints. No longer a lone soldier in a small battle, all of these self-taught, self-directed individuals had to figure out how to work within a team environment.

I learned JavaScript the way many did in the late 1990s: I taught myself. Because JavaScript was so new, educational resources were scarce. I, like many other developers, learned by exploring the intricacies of Internet Explorer and Netscape Navigator on my own. I experimented, theorized, and experimented again until I discovered how things worked. Luckily for me, this curiosity and diligence turned into my first job.

For the first five years of my professional career, I was “the JavaScript guy.” No one in either of my first two companies could match my depth of knowledge in JavaScript and web development in general. All problems, from very simple to very difficult, ended up on my desk to solve by myself. It was both empowering as a fresh-from-college kid and terrifying because I had no one to bounce ideas off of or anyone to ask for help if I got stuck. I did the best that I could, knowing that I was the only one who could do it.

During those five years, I honed my craft. I came up with ways of doing things that made sense to me and my workflow. I didn’t have to worry about what anyone else thought of my code, because no one had enough knowledge to code review or fix what I had written. I was a hacker in its purest sense: I wrote code the way I wanted and wouldn’t hear of changing it.

In year six of my professional career, I switched jobs and ended up on a team where everyone was expected to contribute code in all aspects of the project. No longer able to focus on JavaScript and web development, I found myself writing server-side code and SQL queries most of the time. Meanwhile, traditionally backend-focused developers were being forced to write web code. This experience really opened my eyes: the way I used to write code wasn’t the way the rest of the team wrote code, and that was a problem.

I quickly realized that to be more effective on the team, I had to start writing code the way the rest of the team wrote code. Server-side code and SQL were a bit alien to me, so I adopted the patterns of those around me who knew what they were doing. At the same time, I started talking to the other engineers about adopting coding patterns for HTML, CSS, and JavaScript. I even added JavaScript linting into the build process to enforce our standards—the first test of web code ever at the company. And soon, the team was working as a well-oiled machine.

When I arrived at Yahoo! in 2006, I came with a specific idea of how things should work when I got there. What I found was a completely different animal altogether. The My Yahoo! team, the first team I worked on, was much larger than any I had worked on before. There were already pseudoguidelines in place, and I had a lot to learn. New technologies, new processes, and new tools were presented to me on a daily basis. I was overwhelmed and resigned myself to spending some time learning about this new environment and soaking up as much knowledge as I could from my colleagues.

After a few months, I started to find problems. The processes I had finally become accustomed to weren’t working all the time. There were a lot of people doing things in different ways, and that caused bugs. My manager, noticing this trend, pulled me aside one day and said he’d like me to take lead on cleaning up our development. His words, still inspiring to me, were, “When you write code, things just work—they rarely have bugs. I want everyone to write code like you do.” And with that, I set out to add some structure to the My Yahoo! frontend development team.

The success I had working on the My Yahoo! team ultimately led to my being chosen as the frontend tech lead for the Yahoo! home page redesign of 2008. This assignment really put my organizational and code quality skills to the test, as we had more than 20 frontend engineers working with the same code. After a few months of learning and adjusting, the team reached such a high level of productivity and quality that many were amazed. Not only did all code look remarkably similar regardless of who wrote it, but most developers were capable of quickly switching to someone else’s work to fix bugs or implement new features. What we accomplished as an engineering team over the course of a couple years is still one of the highlights of my career.

It was during my time at Yahoo!, working on large teams, that I accumulated the tips and techniques discussed in this book. The topics highlight how I transformed myself from a hacker, always doing things his own way, to a software engineer, a team player who gave up some of himself so that the team could function at a higher level. And that’s really what this book is about: how to write JavaScript as part of a team.

The hard truth that developers often don’t understand is that we spend most of our time maintaining code. It’s rare that you get to open up a text editor and start writing code from scratch. Most of the time, you’re building on code that’s already there. Writing code in a maintainable away allows you, and others who will work on your code after you, to easily pick up where the code leaves off. As I used to always tell my colleagues at Yahoo!: “When you come to work, you’re not writing code for you, you’re writing code for those who come after you.”

This book is a collection and discussion of code conventions for JavaScript. One of the most popular code convention documents, Code Conventions for the Java Programming Language, lists the following reasons that code conventions are important:

  • Eighty percent of the lifetime cost of a piece of software goes to maintenance.

  • Hardly any software is maintained for its whole life by the original author.

  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

  • If you ship your source code as a product, you need to make sure that it is as well packaged and clean as any other product you create.

This reasoning still rings true today. The conventions discussed in this book are all aimed at helping you and your team write JavaScript in the most effective way possible.

Because you’re reading this book, you probably are open to the suggestions contained herein. Keep in mind that these techniques are really aimed at a multideveloper environment in which there are many engineers all working on the same code. Being a part of a team means making decisions that are best not for you, but for the team as a whole. And that sometimes means sacrificing your preferences, your ideas, and your ego. What you receive in return is a high-functioning team capable of doing great things, and I hope this book will help you along that road.

The best content for your career. Discover unlimited learning on demand for around $1/day.