Book Image

Clean Code in JavaScript

By : James Padolsey
Book Image

Clean Code in JavaScript

By: James Padolsey

Overview of this book

Building robust apps starts with creating clean code. In this book, you’ll explore techniques for doing this by learning everything from the basics of JavaScript through to the practices of clean code. You’ll write functional, intuitive, and maintainable code while also understanding how your code affects the end user and the wider community. The book starts with popular clean-coding principles such as SOLID, and the Law of Demeter (LoD), along with highlighting the enemies of writing clean code such as cargo culting and over-management. You’ll then delve into JavaScript, understanding the more complex aspects of the language. Next, you’ll create meaningful abstractions using design patterns, such as the Class Pattern and the Revealing Module Pattern. You’ll explore real-world challenges such as DOM reconciliation, state management, dependency management, and security, both within browser and server environments. Later, you’ll cover tooling and testing methodologies and the importance of documenting code. Finally, the book will focus on advocacy and good communication for improving code cleanliness within teams or workplaces, along with covering a case study for clean coding. By the end of this book, you’ll be well-versed with JavaScript and have learned how to create clean abstractions, test them, and communicate about them via documentation.
Table of Contents (26 chapters)
1
Section 1: What is Clean Code Anyway?
7
Section 2: JavaScript and Its Bits
13
Section 3: Crafting Abstractions
16
Section 4: Testing and Tooling
20
Section 5: Collaboration and Making Changes

Creating clear hierarchies

To test any code base, we would likely need to write a large number of assertions. Theoretically, we could have a long list of assertions and nothing else. However, doing this may make it quite difficult to read, write, and analyze the reports of tests. To prevent such confusion, it is common for testing libraries to provide some scaffolding abstractions around assertions. For example, BDD-flavoured libraries such as Jasmine and Jest supply two pieces of scaffolding: the it block and the describe block. These are just functions to which we pass a description and callback, but together, they enable a hierarchical tree of tests that makes it far easier to comprehend what's going on. Testing a sum function using this pattern might be done like so:

// A singular test or "spec":
describe('sum()', () => {
it('adds two numbers...